一共有三种传入方式:
1、指定传入的类型 ---直接显示对象的数据类型
2、参数模板化 -----将对象中的参数变为模板进行传递
3、整个类模板化 ---将这个对象类型模板化进行传递
#include <iostream>
using namespace std;
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;
T2 m_age;
};
//指定参数类型最常用
//1、指定传入类型(最常用)
void printPerson (Person<string, int> &p)
{
p.showPerson();
}
void test01 ()
{
Person <string, int> p("sunwukong", 22);
printPerson(p);
}
//2、参数模板化
template <class T1, class T2>
void printPerson2 (Person <T1, T2> &p)
{
p.showPerson();
}
void test02 ()
{
Person <string, int> p("zhubajie", 33);
printPerson2(p);
}
//3、整个类模板化
template <class T>
void printPerson3 (T &p)
{
p.showPerson();
}
void test03 ()
{
Person <string, int> p("tangsheng", 33);
printPerson3(p);
}
int main ()
{
test03();
return 0;
}
总结:
通过类模板创建的对象,可以有三种方式向函数中进行传参
使用比较广泛的时第一种:指定传入的类型