15.2.6 类模板成员函数的类外实现
技巧:任何时候,用到类模板,都需要指定T的数据类型。
所以在类外实现成员函数时,加作用域时用到了类模板,所以作用域后面要指定类型。
除此之外,参数列表也要指定类型。
#include <iostream>
#include <string>
using namespace std;
template<class T1, class T2>
class Person
{
public:
Person(T1 name, T2 age);
void showPerson();
T1 name;
T2 age;
};
//类模板成员函数的类外实现
template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
template<class T1, class T2>
void Person<T1, T2>::showPerson()
{
cout << "姓名:" << this->name << endl;
cout << "年龄:" << this->age << endl;
}
调用一下:
int main()
{
Person<string, int>p("Tom", 20);
p.showPerson();
}