学习目标:
类模板实例化出的对象,向函数传参的方式
一共有三种传参方式:
1.指定传入的类型---直接显示对象的数据类型(推荐)
2.参数模板化---将对象中的参数变为模板进行传递
3.整个模板化---将这个对象类型模板化进行传递
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 //类模板的对象做函数的传递方式 6 template<class T1,class T2> 7 class Person 8 { 9 public: 10 11 Person(T1 name, T2 age) 12 { 13 this->m_Name = name; 14 this->m_Age = age; 15 } 16 17 void showPerson(void) 18 { 19 cout << "姓名:" << this->m_Name << endl; 20 cout << "年龄:" << this->m_Age << endl; 21 } 22 23 T1 m_Name; 24 T2 m_Age; 25 }; 26 27 //1.指定传入的类型 28 void printPerson1(Person<string, int>&p) 29 { 30 p.showPerson(); 31 } 32 33 void test_01(void) 34 { 35 Person<string, int>p("孙悟空",1000); 36 printPerson1(p); 37 } 38 39 //2.参数模板化 40 template<class T1,class T2> 41 void printPerson2(Person<T1, T2>&p) 42 { 43 p.showPerson(); 44 } 45 46 void test_02(void) 47 { 48 Person<string, int>p("猪八戒", 1500); 49 printPerson2(p); 50 } 51 52 //3.整个类模板化 53 template<class T> 54 void printPerson3(T &p) 55 { 56 p.showPerson(); 57 } 58 59 void test_03(void) 60 { 61 Person<string, int>p("唐僧", 2000); 62 printPerson3(p); 63 } 64 65 int main(void) 66 { 67 test_01(); 68 test_02(); 69 test_03(); 70 71 system("pause"); 72 return 0; 73 }