C++提高编程 1 模板
1.1 函数模板
C++另一种编程思想称为 泛型编程 ,主要利用的技术就是模板
C++提供两种模板机制1:函数模板和类模板
1.1.1 函数模板语法
函数模板作用:建立一个通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。
语法:template <typename T>
函数声明或定义
解释:template --- 声明创建模板
typename --- 表明其后面的符号是一种数据类型,可以用class代替
T --- 通用的数据类型,名称可以替换,通常为大写字母
#include<iostream> #include<string> using namespace std; //函数模板 //交换两个整型函数 void swapInt(int &a, int &b) { int temp = a; a = b; b = temp; } //交换两个浮点型函数 void swapDouble(double& a, double& b) { double temp = a; a = b; b = temp; } template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型 void mySwap(T& a, T& b) { T temp = a; a = b; b = temp; } void test1() { //int a = 10; //int b = 20; //swapInt(a, b); //cout << "a=" << a << endl; //cout << "b=" << b << endl; //double c = 1.1; //double d = 2.2; //swapDouble(c, d); //cout << "c=" << c << endl; //cout << "d=" << d << endl; //利用函数模板交换 //两种方式使用函数模板 int a = 10; int b = 20; //1、自动类型推导 //mySwap(a, b); //2、显示指定类型 mySwap<int>(a, b); cout << "a=" << a << endl; cout << "b=" << b << endl; } int main() { test1(); system("pause"); return 0; }
1.1.2 函数模板注意事项
注意事项:
1、自动类型推导,必须推导出一致的数据类型T,才可以使用;
2、模板必须要确定出T的数据类型,才可以使用;
#include<iostream> using namespace std; //函数模板注意事项 //1、自动类型推导,必须推导出一致的数据类型T,才可以使用; template<typename T> //typename可以替换为class class用起来肯定不会错 void mySwap(T& a, T& b) { T temp = a; a = b; b = temp; } void test1() { int a = 10; int b = 20; char c = 'c'; char d = 'd'; mySwap(a, b); //mySwap(a, c); //错误 推导不出一致的T类型 mySwap(c, d); cout << "a=" << a << endl; cout << "b=" << b << endl; cout << "c=" << c << endl; cout << "d=" << d << endl; } //2、模板必须要确定出T的数据类型,才可以使用 template<class T> void func() { cout << "func调用" << endl; } void test2() { //func(); //此时模板无明确的T的数据类型,编译器也无法自动识别。此时只能指定T的数据类型才可使用 func<int>(); } int main() { test1(); test2(); system("pause"); return 0; }
实操:
//实现通用对数组进行排序的函数 //规则 从小到大 //算法 选择排序 //测试 char 数组、int数组 #include<iostream> using namespace std; template<class T> void mySwap(T& a, T& b) { T temp = a; a = b; b = temp; } template<typename T> //typename可替换为class void mySort(T arr[], int len) { for (int i = 0; i < len; i++) { int min = i; //认定最小值下标 for(int j = i + 1; j < len; j++) { if (arr[min] > arr[j]) //认定的最小值比遍历出来的最小值数值要大,说明j下标的元素才是真正的最小值 { min = j; //更新最小值下标 } } if (min != i) { //交换min和i元素 mySwap(arr[min], arr[i]); } } } //提供打印数组模板 template<class T> void printArray(T arr[], int len) { for (int i = 0; i < len; i++) { cout << arr[i] << " "; } cout << endl; } void test1() //测试char数组 { char charArr[] = "bdacfe"; int num = sizeof(charArr) / sizeof(char); mySort(charArr, num); printArray(charArr, num); } void test2() //测试int数组 { int intArr[] = { 3,5,6,2,4,1 }; int num = sizeof(intArr) / sizeof(int); mySort(intArr, num); printArray(intArr, num); } int main() { test1(); test2(); system("pause"); return 0; }
1.1.4 普通函数与函数模板的区别
普通函数与函数模板的区别:
1、普通函数调用时可以发生自动类型转换(隐式类型转换)
2、函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换
3、如果利用显式指定类型的方式,可以发生隐式类型转换
#include<iostream> using namespace std; //普通函数与函数模板的区别: //1、普通函数调用时可以发生隐式类型转换 //2、函数模板 用自动类型推导,不可以发生隐式类型转换 //3、函数模板 用显式指定类型,可以发生隐式类型转换 int myAdd1(int a, int b) { return a + b; } template<class T> T myAdd2(T a, T b) { return a + b; } void test1() { int a = 10; int b = 20; char c = 'c'; //ASCII a=97 c=99 cout << myAdd1(a, c) << endl; //结果109 因为普通函数调用时可以发生隐式类型转换,所以编译器将char ’c‘ 转换为了ASCII码的int值 99 :10 + 99 = 109 //自动类型推导 不会发生隐式类型转换 //cout << myAdd2(a, b) << endl; //显示指定类型 会发生隐式类型转换 cout << myAdd2<int>(a, c) << endl; } int main() { test1(); system("pause"); return 0; }
总结:建议使用显示指定类型的方式,调用函数模板,因为可以自己确定通用类型T
1.1.5 普通函数与函数模板的调用规则
调用规则如下:
1、如果函数模板和普通函数都可以实现,优先调用普通函数
2、可以通过空模板参数列表来强制调用函数模板
3、函数模板也可以发生重载
4、如果函数模板可以产生更好的匹配优先调用函数模板
#include<iostream> using namespace std; //普通函数与函数模板调用规则: //1、如果函数模板和普通函数都可以实现,优先调用普通函数 //2、可以通过空模板参数列表来强制调用函数模板 //3、函数模板也可以发生重载 //4、如果函数模板可以产生更好的匹配,优先调用函数模板 void myPrint(int a, int b) { cout << "调用的普通函数" << endl; } template<class T> void myPrint(T a, T b) { cout << "调用的模板" << endl; } template<class T> void myPrint(T a, T b,T c) { cout << "调用的重载模板" << endl; } void test1() { int a = 10; int b = 20; //myPrint(a, b); //如果函数模板和普通函数都可以实现,优先调用普通函数 //myPrint<>(a, b); //通过空模板参数列表,强制调用函数模板 //myPrint(a, b, 100); //函数模板也可以发生重载 char c1 = 'a'; char c2 = 'b'; //void myPrint(int a, int b)也可调用,把‘a’,‘b’转换为ASCII整型值再交换。 myPrint(c1, c2); //如果函数模板可以产生更好的匹配,优先调用函数模板。此处打印出来的是 调用的重载模板 } int main() { test1(); system("pause"); return 0; }
1.1.6 模板的局限性
模板的通用性不是万能的
template<class T> void f(T a, T b) { a = b; }
上述代码中提供的赋值操作,如果传入的a和b是一个数组,就无法实现了。再例如:
template<class T> void f(T a, T b) { if (a > b) { ... } }
上述代码中,如果T的数据类型传入的是像Person这样的自定义数据类型,也无法正常运行
因此 C++为了解决这种问题,提供模板的重载,可以为这些特定的类型提供具体化的模板
#include<iostream> using namespace std; #include<string> //模板局限性 //模板并不是万能的,有些特定数据类型,需要用具体化方式做特殊实现 class Person { public: Person(string name, int age) { this->m_Name = name; this->m_Age = age; } string m_Name; //姓名 int m_Age; //年龄 }; //对比两个数 template<class T> bool myCompare(T& a, T& b) { if (a == b) { return true; } else { return false; } } //利用具体化的Person的版本实现代码,具体化优先调用 template<> bool myCompare(Person& p1, Person& p2) { if (p1.m_Name == p2.m_Name && p1.m_Age == p2.m_Age) { return true; } else { return false; } } void test1() { int a = 10; int b = 20; bool ret = myCompare(a, b); if (ret) { cout << "a=b" << endl; } else { cout << "a!=b" << endl; } } void test2() { Person p1("Tom", 10); Person p2("Tom", 11); bool ret = myCompare(p1, p2); if (ret) { cout << "p1=p2" << endl; } else { cout << "p1!=p2" << endl; } } int main() { //test1(); test2(); system("pause"); return 0; }
学习模板并不是为了写模板,而是再STL中能够运用系统提供的模板
1.2 类模板
1.2.1 类模板语法
类模板作用:建立一个通用类,类中的成员 数据类型可以不具体制定,用一个虚拟的类型来代表。
#include<iostream> using namespace std; #include<string> //模板局限性 //模板并不是万能的,有些特定数据类型,需要用具体化方式做特殊实现 template<class NameType,class AgeType> class Person { public: Person(NameType name, AgeType age) { this->m_Name = name; this->m_Age = age; } void showPerson() { cout << "name:" << this->m_Name << " " << "age:" << this->m_Age << endl; } NameType m_Name; AgeType m_Age; }; void test1() { Person<string, int>p1("孙悟空", 999); p1.showPerson(); } int main() { test1(); system("pause"); return 0; }
1.2.1 类模板与函数模板区别
类模板与函数模板区别主要有2点:
1、类模板没有自动类型推导的使用方式;
2、类模板在模板参数列表中可以有默认参数;
#include<iostream> using namespace std; #include<string> //类模板与函数模板区别 template<class NameType, class AgeType = int> class Person { public: Person(NameType name, AgeType age) { this->m_Name = name; this->m_Age = age; } void showPerson() { cout << "name:" << this->m_Name << " " << "age:" << this->m_Age << endl; } NameType m_Name; AgeType m_Age; }; //1、类模板没有自动类型推导的使用方式; void test1() { //Person p1("孙悟空", 1000); 错误,无法用自动类型推导 Person<string, int>p1 ("孙悟空", 1000); //正确,只能用显示指针类型 p1.showPerson(); } //2、类模板再模板参数列表中可以有默认参数 void test2() { Person<string>p("猪八戒", 999); p.showPerson(); } int main() { test1(); test2(); system("pause"); return 0; }
1.2.3 类模板中成员函数的创建时机
类模板中成员函数和普通类中成员函数创建时机是有区别的;
1、普通类中的成员函数一开始就可以创建;
2、类模板中的成员函数再调用时才可以创建;
1.2.4 类模板对象做函数参数
类模板实例化出的对象,向函数传参的方式一共有三种:
1、指定传入的类型 --- 直接显示对象的数据类型(使用最广泛,最多)
2、参数模板化 --- 将对象中的参数变为模板进行传递
3、整个类模板化 --- 将这个对象模型 模板化进行传递
#include<iostream> using namespace std; #include<string> template<class T1, class T2> class Person { public: Person(T1 name, T2 age) { this->m_Name = name; this->m_Age = age; } void showPerson() { cout << "name:" << this->m_Name << " " << "age:" << this->m_Age << endl; } T1 m_Name; T2 m_Age; }; //1、指定传入的类型 --- 直接显示对象的数据类型 void printPerson1(Person<string, int>& p) { p.showPerson(); } void test1() { Person<string, int>p("孙悟空", 1000); printPerson1(p); } //2、参数模板化 --- 将对象中的参数变为模板进行传递 template<class T1, class T2> void printPerson2(Person<T1, T2>& p) { p.showPerson(); //此处可查看T1、T2的类型名称typeid().name() cout << "T1的类型为:" << typeid(T1).name() << endl; cout << "T2的类型为:" << typeid(T2).name() << endl; } void test2() { Person<string, int>p("猪八戒", 999); printPerson2(p); } //3、整个类模板化 --- 将这个对象模型 模板化进行传递 template<class T> void printPerson3( T &p) { p.showPerson(); cout << "T的数据类型为:" << typeid(T).name() << endl; } void test3() { Person<string, int>p("唐僧", 30); printPerson3(p); } int main() { test1(); test2(); test3(); system("pause"); return 0; }
1.2.5 类模板与继承
当类模板碰到继承时,需要注意以下几点:
1、当子类继承的父类是一个类模板是,子类在声明的时候,要指定出父类中T的类型
2、如果不指定,编译器无法给子类分配内存
3、如果想灵活指定出父类中T的类型,子类也需要变为类模板
#include<iostream> using namespace std; #include<string> template<class T> class Base { public: T m; }; //class Son :public Base //错误,必须知道父类中的T的类型,才能继承给子类 class Son :public Base<int> { }; void test1() { Son s1; } //如果想灵活指定父类中T的类型,子类也需要变类模板 template<class T1, class T2> class Son2 :public Base<T2> { public: Son2() { cout << "T1的类型为: " << typeid(T1).name() << endl; cout << "T2的类型为: " << typeid(T2).name() << endl; } T1 obj; }; void test2() { Son2<int, char>S2; } int main() { test1(); test2(); system("pause"); return 0; }
总结:如果父类是类模板,子类需要指定出父类中T的数据类型
1.2.6 类模板与成员函数类外实现
#include<iostream> using namespace std; #include<string> template<class T1, class T2> class Person { public: Person(T1 name, T2 age); //{ // this->m_Name = name; // this->m_Age = age; //} void showPerson(); //{ // cout << "姓名:" << this->m_Name << "年龄:" << this->m_Age << endl; //} T1 m_Name; T1 m_Age; }; //构造函数 类外实现 template<class T1, class T2> Person<T1, T2>::Person(T1 name, T2 age) { this->m_Name = name; this->m_Age = age; } //成员函数 类外实现 template<class T1, class T2> void Person<T1, T2>::showPerson() { cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl; } void test1() { Person<string, int> p ("tom", 40 ); p.showPerson(); } int main() { test1(); system("pause"); return 0; }
总结:类模板中成员函数类外实现是,需要加上模板参数列表
1.2.7 类模板分文件编写
问题: 类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到
解决:
解决方法1:直接包含.CPP源文件
Person.h
#pragma once #include <iostream> using namespace std; //分文件 template<class T1, class T2> class Person { public: Person(T1 name, T2 age); void showPerson(); T1 m_Name; T1 m_Age; };
Person.cpp
#include "Person.h" //构造函数 分文件类外实现 template<class T1, class T2> Person<T1, T2>::Person(T1 name, T2 age) { this->m_Name = name; this->m_Age = age; } //成员函数 分文件类外实现 template<class T1, class T2> void Person<T1, T2>::showPerson() { cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl; }
源.cpp
#include<iostream> using namespace std;
//一、直接包含 .cpp源文件 #include "Person.cpp" //类模板分文件编写问题及解决办法 void test1() { Person<string, int>p("Jerry", 18); p.showPerson(); } int main() { test1(); system("pause"); return 0; }
解决方法2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制的。
Person.hpp (此处是把Person.cpp中的内容全部写在了Person.h中。后缀改为.hpp)
#pragma once #include <iostream> #include <string> using namespace std; //分文件 template<class T1, class T2> class Person { public: Person(T1 name, T2 age); void showPerson(); T1 m_Name; T1 m_Age; }; //构造函数 分文件类外实现 template<class T1, class T2> Person<T1, T2>::Person(T1 name, T2 age) { this->m_Name = name; this->m_Age = age; } //成员函数 分文件类外实现 template<class T1, class T2> void Person<T1, T2>::showPerson() { cout << "姓名:" << this->m_Name << " 年龄:" << this->m_Age << endl; }
源.cpp
#include<iostream> using namespace std; //二、将.h和.cpp中的内容写到一起,将后缀改为.hpp文件 #include "Person.hpp" //类模板分文件编写问题及解决办法 void test1() { Person<string, int>p("Jerry", 18); p.showPerson(); } int main() { test1(); system("pause"); return 0; }
总结:主流的解决方式是第二种,将类模板成员函数写到一起,并将后缀改为.hpp
1.2.8 类模板与友元
掌握类模板配合友元函数的类内实现、类外实现
全局函数类内实现 - 直接在类内声明友元即可;
全局函数类外实现 - 需要提前让编译器知道全局函数的存在;
#include<iostream> using namespace std; #include <string> //通过全局函数 打印Person信息 template<class T1, class T2> class Person { //全局函数类内实现 friend void printPerson(Person<T1, T2> p) { cout << "姓名:" << p.m_Name << " 年龄:" << p.m_Age << endl; } public: Person(T1 name, T2 age) { this->m_Name = name; this->m_Age = age; } private: T1 m_Name; T1 m_Age; }; //1、全局函数类内实现 void test1() { Person<string, int>p("Jerry", 30); printPerson(p); } int main() { test1(); system("pause"); return 0; }
类模板数组类封装:
需求:实现一个通用的数组类,要求如下:
1、可以对内置数据类型以及自定义数据类型的数据进行存储;
2、将数组中的数据存储到堆区
3、构造函数中可以传入数组的容量
4、提供对应的拷贝构造函数以及operator= 防止浅拷贝问题
5、提供尾插法、尾删法对数组中的数据进行增加和删除
6、可以通过下标的方式访问数组中的元素
7、可以获取数组中当前元素个数和数组的容量
MyArray.h (MyArray.hpp)
#pragma once #include <iostream> using namespace std; template<class T> class MyArray { public: //有参构造 参数 容量 MyArray(int capacity) { cout << "MyArray的有参构造函数调用" << endl; this->m_Capacity = capacity; this->m_Size = 0; this->pAddress = new T[this->m_Capacity]; } //拷贝构造 MyArray(const MyArray& arr) { cout << "MyArray的拷贝构造函数调用" << endl; this->m_Capacity = arr.m_Capacity; this->m_Size = arr.m_Size; //this->pAddress = arr.pAddress; //指针不能这样直接赋值,会造成浅拷贝的问题,导致堆区数据重复释放 //用深拷贝来解决 重新在堆区开辟个空间让指针维护 this->pAddress = new T[arr.m_Capacity]; //将arr中的数据全部拷贝过来 for (int i = 0; i < this->m_Size; i++) { this->pAddress[i] = arr.pAddress[i]; } } //operator= 防止浅拷贝问题 MyArray& operator=(const MyArray& arr) { cout << "MyArray的operator=调用" << endl; //先判断原来堆区是否有数据,如果有先释放 if (this->pAddress != NULL) { delete[] this->pAddress; this->pAddress = NULL; this->m_Capacity = 0; this->m_Size = 0; } //深拷贝 this->m_Capacity = arr.m_Capacity; this->m_Size = arr.m_Size; this->pAddress = new T[arr.m_Capacity]; for (int i = 0; i < this->m_Size; i++) { this->pAddress[i] = arr.pAddress[i]; } return *this; } //析构函数 ~MyArray() { if (this->pAddress != NULL) { cout << "MyArray的析构函数调用" << endl; delete[] this->pAddress; this->pAddress = NULL; } } private: T* pAddress; //指针指向堆区开辟的真实数组 int m_Capacity; //数组容量 int m_Size; //数组大小 };
MyArray.cpp
#include<iostream> using namespace std; #include <string> #include "MyArray.hpp" void test1() { MyArray <int>arr1(5); MyArray<int>arr2(arr1); MyArray<int>arr3(100); arr3 = arr1; } int main() { test1(); system("pause"); return 0; }

完整版:
MyArray.hpp
#pragma once #include <iostream> using namespace std; template<class T> class MyArray { public: //有参构造 参数 容量 MyArray(int capacity) { cout << "MyArray的有参构造函数调用" << endl; this->m_Capacity = capacity; this->m_Size = 0; this->pAddress = new T[this->m_Capacity]; } //拷贝构造 MyArray(const MyArray& arr) { cout << "MyArray的拷贝构造函数调用" << endl; this->m_Capacity = arr.m_Capacity; this->m_Size = arr.m_Size; //this->pAddress = arr.pAddress; //指针不能这样直接赋值,会造成浅拷贝的问题,导致堆区数据重复释放 //用深拷贝来解决 重新在堆区开辟个空间让指针维护 this->pAddress = new T[arr.m_Capacity]; //将arr中的数据全部拷贝过来 for (int i = 0; i < this->m_Size; i++) { this->pAddress[i] = arr.pAddress[i]; } } //operator= 防止浅拷贝问题 MyArray& operator=(const MyArray& arr) { cout << "MyArray的operator=调用" << endl; //先判断原来堆区是否有数据,如果有先释放 if (this->pAddress != NULL) { delete[] this->pAddress; this->pAddress = NULL; this->m_Capacity = 0; this->m_Size = 0; } //深拷贝 this->m_Capacity = arr.m_Capacity; this->m_Size = arr.m_Size; this->pAddress = new T[arr.m_Capacity]; for (int i = 0; i < this->m_Size; i++) { this->pAddress[i] = arr.pAddress[i]; } return *this; } //尾插法 void Push_Back(const T& val) { //判断容量是否已占满 if (this->m_Capacity == this->m_Size) { return; } this->pAddress[this->m_Size] = val; //在数组末尾插入数据 this->m_Size++; //更新数组大小 } //尾删法 void Pop_Back() { //让用户访问不到最后一个元素,即为尾删。逻辑删除 if (this->m_Size == 0) { return; } this->m_Size--; } //通过下标方式访问数组中的元素 arr[0] = 100 T& operator[](int index) { return this->pAddress[index]; } //返回数组容量 int getCapacity() { return this->m_Capacity; } //返回数组大小 int getSize() { return this->m_Size; } //析构函数 ~MyArray() { if (this->pAddress != NULL) { cout << "MyArray的析构函数调用" << endl; delete[] this->pAddress; this->pAddress = NULL; } } private: T* pAddress; //指针指向堆区开辟的真实数组 int m_Capacity; //数组容量 int m_Size; //数组大小 };
MyArray.cpp
#include<iostream> using namespace std; #include <string> #include "MyArray.hpp" void printIntArray(MyArray <int>& arr) { for (int i = 0; i < arr.getSize(); i++) { cout << arr[i] << endl; } } void test1() { MyArray <int>arr1(5); for (int i = 0; i < 5; i++) { //利用尾插法向数组中插入数据 arr1.Push_Back(i); } cout << "arr1的打印输出为:" << endl; printIntArray(arr1); cout << "arr1的容量为:" << arr1.getCapacity() << endl; cout << "arr1的大小为:" << arr1.getSize() << endl; MyArray<int>arr2(arr1); cout << "arr2的打印输出为:" << endl; printIntArray(arr2); //尾删 arr2.Pop_Back(); cout << "arr2尾删后打印输出为:" << endl; cout << "arr2的容量为:" << arr2.getCapacity() << endl; cout << "arr2的大小为:" << arr2.getSize() << endl; //MyArray<int>arr3(100); //arr3 = arr1; } //测试自定义数据类型 class Person { public: Person() {}; //默认构造空实现,因为在构造这个空数组的时候,并没有具体对象属性输入,此时调用默认构造函数来构建数组元素 Person(string name, int age) { this->m_Name = name; this->m_Age = age; } string m_Name; int m_Age; }; void printPersomArray(MyArray<Person>& arr) { for (int i = 0; i < arr.getSize(); i++) { cout << "姓名:" << arr[i].m_Name << "年龄:" << arr[i].m_Age << endl; } } void test2() { MyArray<Person> arr(10); Person p1("张三", 10); Person p2("李四", 20); Person p3("王五", 30); Person p4("赵六", 40); Person p5("孙七", 50); //将数据插入到数组中 arr.Push_Back(p1); arr.Push_Back(p2); arr.Push_Back(p3); arr.Push_Back(p4); arr.Push_Back(p5); //打印数组 printPersomArray(arr); //输出容量 cout << "arr的容量为:" << arr.getCapacity() << endl; //输出大小 cout << "arr的大小为:" << arr.getSize() << endl; } int main() { test1(); test2(); system("pause"); return 0; }
打印结果:


浙公网安备 33010602011771号