类模板对象做函数参数:
指定传入的类型:
#include<iostream>
#include<string>
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 << "name=" << this->m_Name << endl;
cout << "age=" << this->m_Age << endl;
}
T1 m_Name;
T2 m_Age;
};
//指定传入的类型
void printPerson(Person<string, int>&p)
{
p.showPerson();
}
void test01()
{
Person<string, int>p1("孙大圣", 9999);
//类模板对象做函数参数
printPerson(p1);
}
int main()
{
test01();
}
参数模板化:
#include<iostream>
#include<string>
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 << "name=" << this->m_Name << endl;
cout << "age=" << this->m_Age << endl;
}
T1 m_Name;
T2 m_Age;
};
//参数模板化
template<class T1,class T2>
void printPerson2(Person<T1, T2>&p)
{
p.showPerson();
}
void test02()
{
Person<string, int>p("猪八戒啊", 9999);
printPerson2(p);
}
int main()
{
test02();
}
3整个类模板化:
#include<iostream>
#include<string>
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 << "name=" << this->m_Name << endl;
cout << "age=" << this->m_Age << endl;
}
T1 m_Name;
T2 m_Age;
};
//3,整个类模板化
template<class T>
void printPerson3(T& p)
{
p.showPerson();
}
void test03()
{
Person<string, int>p("唐僧", 30);
printPerson3(p);
}
int main()
{
test03();
}