当有两个或多个类,其功能相同,但数据类型不同时,可以用类模板,减少编辑代码的工作量,增加程序的可读性和易维护性。
类模板用于实现类数据类型的参数化,类模板在表示如数组,表,图等数据结构时,显得特表重要,这些数据结构的表示和算法不受所包含的数据类型的影响。
类模板的用法:
1.类模板可以做函数参数
template<class T1,class T2>
class Car
{
public:
T1 brand;
T2 year;
public:
Car(T1 b, T2 y)
{
brand = b;
year = y;
}
Car(T1 b)
{
brand = b;
}
};
void fun(Car<string, int> car)//类模板做函数参数
{
cout << "brand: " << car.brand << endl;
cout << "tenure of use: " << car.year << endl;
}
2.类模板派生普通类
3.类模板派生类模板
template<class T>
class Dad
{
public:
T Dproperty;
Dad(T property)
{
Dproperty = property;
}
};
template<class T>
class Son:public Dad<T>//类模板派生类模板
{
public:
T sproperty;
Son(T t) :Dad<T>(t)
{
sproperty = t;
}
};
class Gril :public Dad<int>//类模板派生普通类
{
public:
int gproperty;
public:
Gril(int a):Dad<int>(40)
{
gproperty = a;
}
};