类模板

当有两个或多个类,其功能相同,但数据类型不同时,可以用类模板,减少编辑代码的工作量,增加程序的可读性和易维护性。

类模板用于实现类数据类型的参数化,类模板在表示如数组,表,图等数据结构时,显得特表重要,这些数据结构的表示和算法不受所包含的数据类型的影响。

类模板的用法:

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;
}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值