• C++阶段05笔记01【C++提高编程资料(模板概念、函数模板、类模板)】


    C++| 匠心之作 从0到1入门学编程【视频+课件+笔记+源码】

    目录

    01、模板

    1.1、模板的概念

    1.2、函数模板

    1.2.1、函数模板语法

    1.2.2、函数模板注意事项

    1.2.3、函数模板案例

    1.2.4、普通函数与函数模板的区别

    1.2.5、普通函数与函数模板的调用规则

    1.2.6、模板的局限性

    1.3、类模板

    1.3.1、类模板语法

    1.3.2、类模板与函数模板区别

    1.3.3、类模板中成员函数创建时机

    1.3.4、类模板对象做函数参数

    1.3.5、类模板与继承

    1.3.6、类模板成员函数类外实现

    1.3.7、类模板分文件编写

    1.3.8、类模板与友元

    1.3.9、类模板案例


    C++提高编程:本阶段主要针对C++泛型编程和STL技术做详细讲解,探讨C++更深层的使用。

    01、模板

    1.1、模板的概念

    模板就是建立通用的模具,大大提高复用性

    例如生活中的模板。一寸照片模板:

    PPT模板:

     

    模板的特点:1.模板不可以直接使用,它只是一个框架;2.模板的通用并不是万能的。

    1.2、函数模板

    C++另一种编程思想称为泛型编程 ,主要利用的技术就是模板。C++提供两种模板机制:函数模板类模板

    1.2.1、函数模板语法

    函数模板作用:建立一个通用函数,其函数返回值类型和形参类型可以不具体制定,用一个虚拟的类型来代表。

    语法:

    1.  template<typename T>
    2.  函数声明或定义

    解释:

    1. template——声明创建模板;
    2. typename——表面其后面的符号是一种数据类型,可以用class代替;
    3. T——通用的数据类型,名称可以替换,通常为大写字母。

    示例:

    1. #include
    2. using namespace std;
    3. //交换两个整型数据函数
    4. void swapInt(int &a, int &b) {
    5. int temp = a;
    6. a = b;
    7. b = temp;
    8. }
    9. //交换两个浮点型数据函数
    10. void swapDouble(double &a, double &b) {
    11. double temp = a;
    12. a = b;
    13. b = temp;
    14. }
    15. //利用模板提供通用的交换函数 //函数模板
    16. template <typename T>//声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型.
    17. void mySwap(T &a, T &b) {
    18. T temp = a;
    19. a = b;
    20. b = temp;
    21. }
    22. void test01() {
    23. int a = 10;
    24. int b = 20;
    25. swapInt(a, b);
    26. cout << "a = " << a << endl;
    27. cout << "b = " << b << endl;
    28. double c = 1.1;
    29. double d = 2.2;
    30. swapDouble(c, d);
    31. cout << "c = " << c << endl;
    32. cout << "d = " << d << endl;
    33. //利用函数模板实现交换,两种方式使用函数模板:
    34. //1、自动类型推导
    35. mySwap(a, b);
    36. cout << "a = " << a << endl;
    37. cout << "b = " << b << endl;
    38. //2、显示指定类型
    39. mySwap<int>(a, b);
    40. cout << "a = " << a << endl;
    41. cout << "b = " << b << endl;
    42. }
    43. int main() {
    44. test01();
    45. system("pause");
    46. return 0;
    47. }

    总结:

    1. 函数模板利用关键字template;

    2. 使用函数模板有两种方式:自动类型推导、显示指定类型;

    3. 模板的目的是为了提高复用性,将类型参数化。

    1.2.2、函数模板注意事项

    注意事项:

    1. 自动类型推导,必须推导出一致的数据类型T才可以使用;

    2. 模板必须要确定出T的数据类型,才可以使用。

    示例:

    1. #include
    2. using namespace std;
    3. //函数模板注意事项
    4. //1、自动类型推导,必须推导出一致的数据类型T才可以使用;
    5. //2、模板必须要确定出T的数据类型才可以使用。
    6. //利用模板提供通用的交换函数
    7. template <class T>//typename可以被替换成class
    8. void mySwap(T &a, T &b) {
    9. T temp = a;
    10. a = b;
    11. b = temp;
    12. }
    13. // 1、自动类型推导,必须推导出一致的数据类型T才可以使用
    14. void test01() {
    15. int a = 10;
    16. int b = 20;
    17. char c = 'c';
    18. mySwap(a, b);//正确!可以推导出一致的T.
    19. //mySwap(a, c);//错误,不能推导出一致的T类型
    20. cout << "a = " << a << endl;
    21. cout << "b = " << b << endl;
    22. }
    23. // 2、模板必须要确定出T的数据类型才可以使用
    24. template <class T>
    25. void func() {
    26. cout << "func调用!" << endl;
    27. }
    28. void test02() {
    29. //func();//错误,模板不能独立使用,必须确定出T的类型
    30. func<int>(); //利用显示指定类型的方式,给T一个类型,才可以使用该模板
    31. }
    32. int main() {
    33. test01();
    34. test02();
    35. system("pause");
    36. return 0;
    37. }

    总结:使用模板时必须确定出通用数据类型T,并且能够推导出一致的类型。

    1.2.3、函数模板案例

    案例描述:

    1. 利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序;

    2. 排序规则从大到小,排序算法为选择排序

    3. 分别利用char数组int数组进行测试。

    示例:

    1. #include
    2. using namespace std;
    3. //实现通用对数组进行排序的函数
    4. //规则:从大到小
    5. //算法:选择排序
    6. //测试:char数组、int数组
    7. //交换的函数模板
    8. template <typename T>
    9. void mySwap(T &a, T &b) {
    10. T temp = a;
    11. a = b;
    12. b = temp;
    13. }
    14. template <class T>//也可以替换成typename
    15. //利用选择排序,进行对数组从大到小的排序
    16. void mySort(T arr[], int len) {
    17. for (int i = 0; i < len; i++) {
    18. int max = i;//认定最大数值的下标
    19. for (int j = i + 1; j < len; j++) {
    20. //认定的最大值比遍历出的数值要小,说明j下标的元素才是真正的最大值
    21. if (arr[max] < arr[j]) {
    22. max = j;//更新最大值下标
    23. }
    24. }
    25. if (max != i) {//如果最大数的下标不是i,则交换两者
    26. mySwap(arr[max], arr[i]);//交换max和i下标元素
    27. }
    28. }
    29. }
    30. //提供打印数组模板
    31. template <typename T>//class
    32. void printArray(T arr[], int len) {
    33. for (int i = 0; i < len; i++) {
    34. cout << arr[i] << " ";
    35. }
    36. cout << endl;
    37. }
    38. void test01() {//测试char数组
    39. char charArr[] = "bdcfeagh";//badcfe
    40. int num = sizeof(charArr) / sizeof(char);
    41. mySort(charArr, num);
    42. printArray(charArr, num);
    43. }
    44. void test02() {//测试int数组
    45. int intArr[] = {7, 5, 8, 1, 3, 9, 2, 4, 6};
    46. int num = sizeof(intArr) / sizeof(int);
    47. mySort(intArr, num);
    48. printArray(intArr, num);
    49. }
    50. int main() {
    51. test01();
    52. test02();
    53. system("pause");
    54. return 0;
    55. }

    总结:模板可以提高代码复用,需要熟练掌握。

    1.2.4、普通函数与函数模板的区别

    普通函数与函数模板区别:

    • 普通函数调用时可以发生自动类型转换(隐式类型转换);

    • 函数模板调用时,如果利用自动类型推导,不会发生隐式类型转换;

    • 如果利用显示指定类型的方式,可以发生隐式类型转换。

    示例:

    1. #include
    2. using namespace std;
    3. //普通函数与函数模板区别
    4. //1、普通函数调用可以发生隐式类型转换
    5. //2、函数模板用自动类型推导,不可以发生隐式类型转换
    6. //3、函数模板用显示指定类型,可以发生隐式类型转换
    7. //普通函数
    8. int myAdd01(int a, int b) {
    9. return a + b;
    10. }
    11. //函数模板
    12. template <class T>
    13. T myAdd02(T a, T b) {
    14. return a + b;
    15. }
    16. //使用函数模板时,如果用自动类型推导,不会发生自动类型转换,即隐式类型转换
    17. void test01() {
    18. int a = 10;
    19. int b = 20;
    20. char c = 'c';//'c'对应ASCII码99
    21. cout << myAdd01(a, c) << endl;//正确,将char类型的'c'隐式转换为int类型,'c'对应ASCII码99
    22. //自动类型推导,不会发生隐式类型转换
    23. //myAdd02(a, c);//报错,使用自动类型推导时,不会发生隐式类型转换
    24. //显示指定类型,会发生隐式类型转换
    25. myAdd02<int>(a, c);//正确,如果用显示指定类型,可以发生隐式类型转换
    26. }
    27. int main() {
    28. test01();
    29. system("pause");
    30. return 0;
    31. }

    总结:建议使用显示指定类型的方式,调用函数模板,因为可以自己确定通用类型T。

    1.2.5、普通函数与函数模板的调用规则

    调用规则如下:

    1. 如果函数模板和普通函数都可以实现,优先调用普通函数;

    2. 可以通过空模板参数列表来强制调用函数模板;

    3. 函数模板也可以发生重载;

    4. 如果函数模板可以产生更好的匹配,优先调用函数模板。

    示例:

    1. #include
    2. using namespace std;
    3. //普通函数与函数模板调用规则
    4. //1、如果函数模板和普通函数都可以调用,优先调用普通函数;
    5. //2、可以通过空模板参数列表强制调用函数模板;
    6. //3、函数模板也可以发生函数重载;
    7. //4、如果函数模板可以产生更好的匹配,优先调用函数模板。
    8. void myPrint(int a, int b) {
    9. cout << "调用的普通函数!" << endl;
    10. }
    11. template <typename T>
    12. void myPrint(T a, T b) {
    13. cout << "调用的模板!" << endl;
    14. }
    15. template <typename T>
    16. void myPrint(T a, T b, T c) {
    17. cout << "调用重载的模板!" << endl;
    18. }
    19. void test01() {
    20. //1、如果函数模板和普通函数都可以实现,优先调用普通函数
    21. //注意:如果告诉编译器普通函数是有的,但只是声明没有实现,或者不在当前文件内实现,就会报错找不到!
    22. int a = 10;
    23. int b = 20;
    24. myPrint(a, b);//调用普通函数
    25. //2、可以通过空模板参数列表来强制调用函数模板
    26. myPrint<>(a, b);//调用函数模板
    27. //3、函数模板也可以发生重载
    28. int c = 30;
    29. myPrint(a, b, c);//调用重载的函数模板
    30. //4、如果函数模板可以产生更好的匹配,优先调用函数模板
    31. char c1 = 'a';
    32. char c2 = 'b';
    33. myPrint(c1, c2);//调用函数模板
    34. }
    35. int main() {
    36. test01();
    37. system("pause");
    38. return 0;
    39. }

    总结:既然提供了函数模板,最好就不要提供普通函数,否则容易出现二义性。

    1.2.6、模板的局限性

    局限性:模板的通用性并不是万能的。

    例如:

    1. template<class T>
    2. void f(T a, T b) {
    3. a = b;
    4. }

    在上述代码中提供的赋值操作,如果传入的a和b是一个数组,就无法实现了。

    再例如:

    1. template<class T>
    2. void f(T a, T b) {
    3. if(a > b) {
    4. ...
    5. }
    6. }

    在上述代码中,如果T的数据类型传入的是像Person这样的自定义数据类型,也无法正常运行。

    因此C++为了解决这种问题,提供模板的重载,可以为这些特定的类型提供具体化的模板

    示例:

    1. #include
    2. #include
    3. using namespace std;
    4. //模板局限性
    5. //模板并不是万能的,有些特定数据类型,需要用具体化的方式做特殊实现
    6. class Person {
    7. public:
    8. Person(string name, int age) {
    9. this->m_Name = name;
    10. this->m_Age = age;
    11. }
    12. string m_Name;//姓名
    13. int m_Age;//年龄
    14. };
    15. //普通函数模板
    16. template <class T>
    17. bool myCompare(T &a, T &b) {//对比两个数据是否相等函数
    18. if (a == b) {
    19. return true;
    20. } else {
    21. return false;
    22. }
    23. }
    24. //具体化,显示具体化的原型和定意思以template<>开头,并通过名称来指出类型
    25. //具体化优先于常规模板
    26. //利用具体化Person的版本实现代码,具体化优先调用
    27. template <>
    28. bool myCompare(Person &p1, Person &p2) {
    29. if (p1.m_Name == p2.m_Name && p1.m_Age == p2.m_Age) {
    30. return true;
    31. } else {
    32. return false;
    33. }
    34. }
    35. void test01() {
    36. int a = 10;
    37. int b = 20;
    38. //内置数据类型可以直接使用通用的函数模板
    39. bool ret = myCompare(a, b);
    40. if (ret) {
    41. cout << "a == b" << endl;
    42. } else {
    43. cout << "a != b" << endl;
    44. }
    45. }
    46. void test02() {
    47. Person p1("Tom", 10);
    48. Person p2("Tom", 10);
    49. //自定义数据类型,不会调用普通的函数模板
    50. //可以创建具体化的Person数据类型的模板,用于特殊处理这个类型
    51. bool ret = myCompare(p1, p2);
    52. if (ret) {
    53. cout << "p1 == p2" << endl;
    54. } else {
    55. cout << "p1 != p2" << endl;
    56. }
    57. }
    58. int main() {
    59. test01();//a != b
    60. test02();//p1 == p2
    61. system("pause");
    62. return 0;
    63. }

    总结:

    1. 利用具体化的模板,可以解决自定义类型的通用化;

    2. 学习模板并不是为了写模板,而是在STL能够运用系统提供的模板。

    1.3、类模板

    1.3.1、类模板语法

    类模板作用:建立一个通用类,类中的成员数据类型可以不具体制定,用一个虚拟的类型来代表。

    语法:

    1.  template<typename T>
    2.  类

    解释:

    1. template——声明创建模板;
    2. typename——表面其后面的符号是一种数据类型,可以用class代替;
    3. T——通用的数据类型,名称可以替换,通常为大写字母。

    示例:

    1. #include
    2. #include
    3. using namespace std;
    4. //类模板
    5. template <class NameType, class AgeType>
    6. class Person {
    7. public:
    8. Person(NameType name, AgeType age) {
    9. this->mName = name;
    10. this->mAge = age;
    11. }
    12. void showPerson() {
    13. cout << "name:" << this->mName << ",age:" << this->mAge << endl;
    14. }
    15. public:
    16. NameType mName;
    17. AgeType mAge;
    18. };
    19. void test01() {
    20. //指定NameType为string类型,AgeType为int类型
    21. Personint> P1("孙悟空", 999);
    22. P1.showPerson();
    23. }
    24. int main() {
    25. test01();
    26. system("pause");
    27. return 0;
    28. }

    总结:类模板和函数模板语法相似,在声明模板template后面加类,此类称为类模板

    1.3.2、类模板与函数模板区别

    类模板与函数模板区别主要有两点:1.类模板没有自动类型推导的使用方式;2.类模板在模板参数列表中可以有默认参数。

    示例:

    1. #include
    2. #include
    3. using namespace std;
    4. //类模板
    5. template <class NameType, class AgeType = int>
    6. class Person {
    7. public:
    8. Person(NameType name, AgeType age) {
    9. this->mName = name;
    10. this->mAge = age;
    11. }
    12. void showPerson() {
    13. cout << "name:" << this->mName << ",age:" << this->mAge << endl;
    14. }
    15. public:
    16. NameType mName;
    17. AgeType mAge;
    18. };
    19. //区别1、类模板没有自动类型推导的使用方式
    20. void test01() {
    21. //Person p("孙悟空", 1000);//错误,类模板使用时不可以用自动类型推导
    22. Personint> p("孙悟空", 1000);//必须使用显示指定类型的方式使用类模板
    23. p.showPerson();
    24. }
    25. //区别2、类模板在模板参数列表中可以有默认参数
    26. void test02() {
    27. Person p("猪八戒", 999);//类模板中的模板参数列表可以指定默认参数
    28. p.showPerson();
    29. }
    30. int main(){
    31. test01();
    32. test02();
    33. system("pause");
    34. return 0;
    35. }

    总结:1.类模板使用只能用显示指定类型方式;2.类模板中的模板参数列表可以有默认参数。

    1.3.3、类模板中成员函数创建时机

    类模板中成员函数和普通类中成员函数创建时机是有区别的:

    1. 普通类中的成员函数一开始就可以创建;
    2. 类模板中的成员函数在调用时才创建。

    示例: ​

    1. #include
    2. #include
    3. using namespace std;
    4. //类模板中成员函数创建时机:类模板中成员函数在调用时才去创建
    5. class Person1 {
    6. public:
    7. void showPerson1() {
    8. cout << "Person1 show!" << endl;
    9. }
    10. };
    11. class Person2 {
    12. public:
    13. void showPerson2() {
    14. cout << "Person2 show!" << endl;
    15. }
    16. };
    17. template <class T>
    18. class MyClass {
    19. public:
    20. T obj;
    21. //类模板中的成员函数,并不是一开始就创建的,而是在模板调用时再生成
    22. void fun1() { obj.showPerson1(); }
    23. void fun2() { obj.showPerson2(); }
    24. };
    25. void test01() {
    26. MyClass m;
    27. m.fun1();
    28. //m.fun2();//编译会出错,说明函数调用才会去创建成员函数
    29. }
    30. int main() {
    31. test01();
    32. system("pause");
    33. return 0;
    34. }

    总结:类模板中的成员函数并不是一开始就创建的,在调用时才去创建。

    1.3.4、类模板对象做函数参数

    学习目标:类模板实例化出的对象,向函数传参的方式。

    一共有三种传入方式:

    1. 指定传入的类型——直接显示对象的数据类型;

    2. 参数模板化——将对象中的参数变为模板进行传递;

    3. 整个类模板化——将这个对象类型 模板化进行传递。

    示例:

    1. #include
    2. #include
    3. using namespace std;
    4. //类模板对象做函数参数
    5. //1、指定传入类型
    6. //2、参数模板化
    7. //3、整个类模板化
    8. //类模板
    9. //template
    10. // class Person {
    11. // public:
    12. // Person(T1 name, T2 age) {
    13. // this->mName = name;
    14. // this->mAge = age;
    15. // }
    16. // void showPerson() {
    17. // cout << "姓名name:" << this->mName << ",年龄age:" << this->mAge << endl;
    18. // }
    19. // public:
    20. // T1 mName;
    21. // T2 mAge;
    22. // };
    23. template <class NameType, class AgeType = int>
    24. class Person {
    25. public:
    26. Person(NameType name, AgeType age) {
    27. this->mName = name;
    28. this->mAge = age;
    29. }
    30. void showPerson() {
    31. cout << "姓名name:" << this->mName << ",年龄age:" << this->mAge << endl;
    32. }
    33. public:
    34. NameType mName;
    35. AgeType mAge;
    36. };
    37. //1、指定传入的类型
    38. void printPerson1(Personint> &p) {
    39. p.showPerson();
    40. }
    41. void test01() {
    42. Personint> p("孙悟空", 100);
    43. printPerson1(p);
    44. cout << endl;
    45. }
    46. //2、参数模板化
    47. template <class T1, class T2>
    48. void printPerson2(Person &p) {
    49. p.showPerson();
    50. cout << "T1的类型为:" << typeid(T1).name() << endl;//T1的类型为:NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
    51. cout << "T2的类型为:" << typeid(T2).name() << endl;//T2的类型为:i
    52. }
    53. void test02() {
    54. Personint> p("猪八戒", 90);
    55. printPerson2(p);
    56. cout << endl;
    57. }
    58. //3、整个类模板化
    59. template <class T>
    60. void printPerson3(T &p) {
    61. cout << "T的数据类型为:" << typeid(T).name() << endl;
    62. p.showPerson();
    63. }
    64. void test03() {
    65. Personint> p("唐僧", 30);
    66. printPerson3(p);//T的类型为:6PersonINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEiE
    67. cout << endl;
    68. }
    69. int main() {
    70. test01();
    71. test02();
    72. test03();
    73. system("pause");
    74. return 0;
    75. }

    总结:

    1. 通过类模板创建的对象,可以有三种方式向函数中进行传参;

    2. 使用比较广泛是第一种:指定传入的类型。

    1.3.5、类模板与继承

    当类模板碰到继承时,需要注意一下几点:

    1. 当子类继承的父类是一个类模板时,子类在声明的时候,要指定出父类中T的类型;

    2. 如果不指定,编译器无法给子类分配内存;

    3. 如果想灵活指定出父类中T的类型,子类也需变为类模板。

    示例:

    1. #include
    2. using namespace std;
    3. template <class T>
    4. class Base {
    5. T m;
    6. };
    7. //class Son:public Base {};//错误,c++编译需要给子类分配内存,必须知道父类中T的类型才可以向下继承。
    8. //错误,必须要知道父类中的T类型,才能继承给子类
    9. class Son : public Base<int> {};//必须指定一个类型
    10. void test01() {
    11. Son s;
    12. }
    13. //类模板继承类模板,可以用T2指定父类中的T类型
    14. //如果想灵活指定父类中T类型,子类也需要变类模板
    15. template <class T1, class T2>
    16. class Son2 : public Base {
    17. public:
    18. Son2() {
    19. cout << "T1的类型为:" << typeid(T1).name() << endl;
    20. cout << "T2的类型为:" << typeid(T2).name() << endl;
    21. }
    22. T1 obj;
    23. };
    24. void test02() {
    25. Son2<int, char> s2;
    26. }
    27. int main() {
    28. test01();
    29. test02();
    30. system("pause");
    31. return 0;
    32. }

    总结:如果父类是类模板,子类需要指定出父类中T的数据类型。

    1.3.6、类模板成员函数类外实现

    学习目标:能够掌握类模板中的成员函数类外实现。

    示例:

    1. #include
    2. #include
    3. using namespace std;
    4. //类模板中成员函数类外实现
    5. template <class T1, class T2>
    6. class Person {
    7. public:
    8. //成员函数类内声明
    9. Person(T1 name, T2 age);
    10. void showPerson();
    11. public:
    12. T1 m_Name;
    13. T2 m_Age;
    14. };
    15. //构造函数类外实现
    16. template <class T1, class T2>
    17. Person::Person(T1 name, T2 age) {
    18. this->m_Name = name;
    19. this->m_Age = age;
    20. }
    21. //成员函数类外实现
    22. template <class T1, class T2>
    23. void Person::showPerson() {
    24. cout << "姓名:" << this->m_Name << ",年龄:" << this->m_Age << endl;
    25. }
    26. void test01() {
    27. Personint> p("Tom", 20);
    28. p.showPerson();
    29. }
    30. int main() {
    31. test01();
    32. system("pause");
    33. return 0;
    34. }

    总结:类模板中成员函数类外实现时,需要加上模板参数列表。

    1.3.7、类模板分文件编写

    学习目标:掌握类模板成员函数分文件编写产生的问题以及解决方式。

    问题:类模板中成员函数创建时机是在调用阶段,导致分文件编写时链接不到。

    解决:

    • 解决方式1:直接包含.cpp源文件;

    • 解决方式2:将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定的名称,并不是强制。

    示例:

    person.hpp中代码:

    1. #pragma once//防止头文件重复包含
    2. #include
    3. #include
    4. using namespace std;
    5. template <class T1, class T2>
    6. class Person {
    7. public:
    8. Person(T1 name, T2 age);
    9. void showPerson();
    10. public:
    11. T1 m_Name;
    12. T2 m_Age;
    13. };
    14. //构造函数类外实现
    15. template <class T1, class T2>
    16. Person::Person(T1 name, T2 age) {
    17. this->m_Name = name;
    18. this->m_Age = age;
    19. }
    20. //成员函数类外实现
    21. template <class T1, class T2>
    22. void Person::showPerson() {
    23. cout << "姓名:" << this->m_Name << ",年龄:" << this->m_Age << endl;
    24. }

    类模板分文件编写.cpp中代码

    1. #include //类模板分文件编写问题以及解决
    2. using namespace std;
    3. //#include "person.h"
    4. #include "person.cpp"//解决方式1,直接包含cpp源文件
    5. //第一种解决方式:直接包含源文件
    6. //解决方式2,将声明和实现写到一起,文件后缀名改为.hpp
    7. //第二种解决方式:将.h和.cpp中的内容写到一起,将后缀名改为.hpp文件
    8. //#include "person.cpp"
    9. void test01() {
    10. Personint> p("Tom", 10);
    11. p.showPerson();
    12. }
    13. int main() {
    14. test01();
    15. system("pause");
    16. return 0;
    17. }

    总结:主流的解决方式是第二种,将类模板成员函数写到一起,并将后缀名改为.hpp

    1.3.8、类模板与友元

    学习目标:掌握类模板配合友元函数的类内和类外实现。

    1. 全局函数类内实现——直接在类内声明友元即可;
    2. 全局函数类外实现——需要提前让编译器知道全局函数的存在。

    示例:

    1. #include
    2. #include
    3. using namespace std;
    4. //2、全局函数配合友元 类外实现 - 先做函数模板声明,下方在做函数模板定义,在做友元
    5. template <class T1, class T2>
    6. class Person;//提前让编译器知道Person类的存在
    7. //如果声明了函数模板,可以将实现写到后面,否则需要将实现体写到类的前面让编译器提前看到
    8. // template void printPerson2(Person & p);
    9. template <class T1, class T2>
    10. void printPerson2(Person &p) {
    11. cout << "类外实现 ---- 姓名:" << p.m_Name << ",年龄:" << p.m_Age << endl;
    12. }
    13. template <class T1, class T2>
    14. class Person {
    15. //1、全局函数配合友元-类内实现
    16. friend void printPerson(Person &p) {//全局函数类内实现
    17. cout << "姓名:" << p.m_Name << ",年龄:" << p.m_Age << endl;
    18. }
    19. //全局函数配合友元-类外实现
    20. //加空模板参数列表 //如果全局函数是类外实现,需要让编译器提前知道这个函数的存在
    21. friend void printPerson2<>(Person &p);
    22. public:
    23. Person(T1 name, T2 age) {
    24. this->m_Name = name;
    25. this->m_Age = age;
    26. }
    27. private:
    28. T1 m_Name;
    29. T2 m_Age;
    30. };
    31. //1、全局函数在类内实现
    32. void test01() {
    33. Personint> p("Tom", 20);
    34. printPerson(p);
    35. }
    36. //2、全局函数在类外实现
    37. void test02() {
    38. Personint> p("Jerry", 30);
    39. printPerson2(p);
    40. }
    41. int main() {
    42. // test01();
    43. test02();
    44. system("pause");
    45. return 0;
    46. }

    总结:建议全局函数做类内实现,用法简单,而且编译器可以直接识别。

    1.3.9、类模板案例

    案例描述:实现一个通用的数组类,要求如下:

    1. 可以对内置数据类型以及自定义数据类型的数据进行存储;

    2. 将数组中的数据存储到堆区;

    3. 构造函数中可以传入数组的容量;

    4. 提供对应的拷贝构造函数以及operator=防止浅拷贝问题;

    5. 提供尾插法和尾删法对数组中的数据进行增加和删除;

    6. 可以通过下标的方式访问数组中的元素;

    7. 可以获取数组中当前元素个数和数组的容量。

    类模板案例-数组类封装

    示例:

    myArray.hpp中代码

    1. #pragma once//防止头文件重复包含
    2. #include //自己的通用数组类
    3. using namespace std;
    4. template <class T>//声明类模板
    5. class MyArray {
    6. public:
    7. //构造函数,参数:容量
    8. MyArray(int capacity) {
    9. cout << "MyArray有参构造函数调用!" << endl;
    10. this->m_Capacity = capacity;
    11. this->m_Size = 0;
    12. pAddress = new T[this->m_Capacity];
    13. }
    14. //拷贝构造
    15. MyArray(const MyArray &arr) {
    16. cout << "MyArray有参拷贝构造函数调用!" << endl;
    17. this->m_Capacity = arr.m_Capacity;
    18. this->m_Size = arr.m_Size;
    19. this->pAddress = new T[this->m_Capacity];//深拷贝
    20. for (int i = 0; i < this->m_Size; i++) {//将arr数组中的数据都拷贝过来
    21. //如果T为对象,而且还包含指针,必须需要重载=操作符,因为这个等号不是构造而是赋值,
    22. //普通类型可以直接=,但是指针类型需要深拷贝
    23. this->pAddress[i] = arr.pAddress[i];
    24. }
    25. }
    26. //operator=,重载=操作符,防止浅拷贝问题
    27. MyArray &operator=(const MyArray &myarray) {
    28. cout << "MyArray的operator=调用!" << endl;
    29. if (this->pAddress != NULL) {//先判断原来堆区是否有数据,如果有先释放
    30. delete[] this->pAddress;
    31. this->pAddress = NULL;
    32. this->m_Capacity = 0;
    33. this->m_Size = 0;
    34. }
    35. //深拷贝
    36. this->m_Capacity = myarray.m_Capacity;
    37. this->m_Size = myarray.m_Size;
    38. this->pAddress = new T[this->m_Capacity];//arr.m_Capacity
    39. for (int i = 0; i < this->m_Size; i++) {
    40. this->pAddress[i] = myarray[i];//arr.pAddress[i];
    41. }
    42. return *this;
    43. }
    44. //通过下标方式访问数组中的元素
    45. T &operator[](int index) {//重载[]操作符,arr[0] = 100
    46. return this->pAddress[index];//不考虑越界,用户自己去处理
    47. }
    48. //尾插法
    49. void Push_back(const T &val) {
    50. if (this->m_Capacity == this->m_Size) {//判断容量是否等于大小
    51. return;
    52. }
    53. this->pAddress[this->m_Size] = val;//在数组末尾插入数据
    54. this->m_Size++;//更新数组大小
    55. }
    56. //尾删法
    57. void Pop_back() {//让用户访问不到最后一个元素,即为尾删,逻辑删除
    58. if (this->m_Size == 0) {
    59. return;
    60. }
    61. this->m_Size--;
    62. }
    63. //返回数组容量
    64. int getCapacity() {//获取数组容量
    65. return this->m_Capacity;
    66. }
    67. //返回数组大小
    68. int getSize() {//获取数组大小
    69. return this->m_Size;
    70. }
    71. ~MyArray() {//析构函数
    72. if (this->pAddress != NULL) {//将堆区数据释放干净
    73. cout << "MyArray析构函数调用!" << endl;
    74. delete[] this->pAddress;
    75. this->pAddress = NULL;
    76. this->m_Capacity = 0;
    77. this->m_Size = 0;
    78. }
    79. }
    80. private:
    81. T *pAddress;//指针指向堆区开辟的真实数组;指向一个堆空间,这个空间存储真正的数据
    82. int m_Capacity;//数组容量
    83. int m_Size;//数组元素个数(数组大小)
    84. };

    类模板案例—数组类封装.cpp中

    1. #include "myArray.hpp"
    2. #include
    3. void printIntArray(MyArray<int> &arr) {//打印输出函数
    4. for (int i = 0; i < arr.getSize(); i++) {
    5. cout << arr[i] << " ";
    6. }
    7. cout << endl;
    8. }
    9. //测试内置数据类型
    10. void test01() {
    11. MyArray<int> array1(10);
    12. for (int i = 0; i < 10; i++) {
    13. //利用尾插法向数组中插入数据
    14. array1.Push_back(i);
    15. }
    16. cout << "array1打印输出为:" << endl;
    17. printIntArray(array1);
    18. cout << "array1的大小为:" << array1.getSize() << endl;
    19. cout << "array1的容量为:" << array1.getCapacity() << endl;
    20. cout << "--------------------------" << endl;
    21. MyArray<int> array2(array1);//验证拷贝构造函数
    22. array2.Pop_back();//尾删
    23. cout << "array2打印输出:" << endl;
    24. printIntArray(array2);
    25. cout << "array2的大小:" << array2.getSize() << endl;
    26. cout << "array2的容量:" << array2.getCapacity() << endl;
    27. //MyArray array3(100);
    28. //array3 = array1;
    29. }
    30. //测试自定义数据类型
    31. class Person {
    32. public:
    33. Person() {}
    34. Person(string name, int age) {
    35. this->m_Name = name;
    36. this->m_Age = age;
    37. }
    38. public:
    39. string m_Name;
    40. int m_Age;
    41. };
    42. void printPersonArray(MyArray &personArr) {
    43. for (int i = 0; i < personArr.getSize(); i++) {
    44. cout << "姓名:" << personArr[i].m_Name << ",年龄:" << personArr[i].m_Age << endl;
    45. }
    46. }
    47. void test02() {
    48. //创建数组
    49. MyArray pArray(10);
    50. Person p1("孙悟空", 30);
    51. Person p2("韩信", 20);
    52. Person p3("妲己", 18);
    53. Person p4("王昭君", 15);
    54. Person p5("赵云", 24);
    55. //插入数据,将数据插入到数组中
    56. pArray.Push_back(p1);
    57. pArray.Push_back(p2);
    58. pArray.Push_back(p3);
    59. pArray.Push_back(p4);
    60. pArray.Push_back(p5);
    61. printPersonArray(pArray);//打印数组
    62. cout << "pArray的大小:" << pArray.getSize() << endl;//输出容量
    63. cout << "pArray的容量:" << pArray.getCapacity() << endl;//输出大小
    64. }
    65. int main() {
    66. // test01();
    67. test02();
    68. system("pause");
    69. return 0;
    70. }

    总结:能够利用所学知识点实现通用的数组。

  • 相关阅读:
    40-Jenkins-环境变量的使用
    亚马逊跟卖有效找listing,适合各阶段卖家
    磁盘格式化指南:如何正确对磁盘进行分区和初始化?
    我的Vue之旅、02 ES6基础、模块、路径、IO
    零基础都能拿捏的七夕浪漫代码,快去表白或去制造惊喜吧
    [springMVC学习]11、自定义拦截器
    头歌-信息安全技术-用Python实现自己的区块链、支持以太坊的云笔记服务器端开发、编写并测试用于保存云笔记的智能合约、支持以太坊的云笔记小程序开发基础
    IOS常见的bug
    06-JVM-监控及调优案例
    如何成为一个优秀的程序员?
  • 原文地址:https://blog.csdn.net/weixin_44949135/article/details/125977128