类模板作用:类中的成员,数据类型可以不具体制定,用一个虚拟类型来代表
语法:
template<typename T>
类
template<class nametype,class agetype>
class person
{
public:
person(nametype name, agetype age)
{
m_name = name;
m_age = age;
}
void showPerson()
{
cout << m_name << ":" << m_age << endl;
}
nametype m_name;
agetype m_age;
};
int main()
{
person<string, int>p1("tom",18);
p1.showPerson();
return 0;
}
类模板与函数模板的区别
1、类模板没有自动类型推导的使用方式
person p2("sam",22);//错误
2、类模板在模板参数列表中可以有默认参数
template<class nametype,class agetype=int>
person<string>p1("tom",18);
有指定的类型参数就用指定的类型参数,没有的话就用默认的参数