一、类模板
template<typename NameType, typename AgeType>
class Person
{
public:
NameType name;
AgeType age;
Person(NameType name, AgeType age)
{
this->name = name;
this->age = age;
}
void showPerson()
{
cout << "name= " << name << " age= " << age << endl;
}
};
void test()
{
Person<string, int> p1("大帅B", 26);
p1.showPerson();
}
int main()
{
test();
return 0;
}
二、类模板和函数模板的区别
- 类模板的模板参数列表可以有默认参数
- 类模板没有自动类型推导的使用方式
template<class NameType, class AgeType = int>
class Person
{
public:
NameType name;
AgeType age;
Person(NameType name, AgeType age)
{
this->name = name;
this->age = age;
}
void showPerson()
{
cout << "name= " << name << " age= " << age << endl;
}
};
void test()
{
Person<string> p1("葛二蛋", 30);
p1.showPerson();
}
int main()
{
test();
return 0;
}
|