C++ //类模板与函数模板的区别 //1.类模板没有自动类型推导的使用方式 //2.类模板子模板参数中可以有默认参数

 1 //类模板与函数模板的区别
 2 //1.类模板没有自动类型推导的使用方式
 3 //2.类模板子模板参数中可以有默认参数
 4 
 5 #include <iostream>
 6 #include <string>
 7 #include<fstream>
 8 using namespace std;
 9 
10 template<class NameType, class AgeType = int>
11 class Person
12 {
13 public:
14     Person(NameType name, AgeType age)
15     {
16         this->m_Name = name;
17         this->m_Age = age;
18     }
19 
20     void showPerson()
21     {
22         cout << "name: " << this->m_Name << "    age = " << this->m_Age << endl;
23     }
24 
25 
26     NameType m_Name;
27     AgeType m_Age;
28 };
29 
30 //1.类模板没有自动类型推导使用方式
31 void test01()
32 {
33     //Person p("张三", 10); 错误  
34 
35     Person<string, int>p("张三", 100);//只能用指定类型
36     p.showPerson();
37 }
38 
39 
40 //2.类模板在模板参数列表中有默认参数
41 void test02()
42 {
43     Person<string>p("李四", 20);
44     p.showPerson();
45 }
46 
47 
48 
49 int main()
50 {
51 
52     test01();
53     test02();
54 
55 
56     system("pause");
57 
58     return 0;
59 
60 }

 

posted on 2021-08-13 07:14  Bytezero!  阅读(83)  评论(0编辑  收藏  举报