类模板意思是先把类里面的数据类型待定,之后通过模板再来定义数据类型,详情看以下代码。
//类模板的写法
template <class T>
class Cml
{
public:
Cml(T _age = 18, T _weight = 90): age(_age), weight(_weight){}
T getAge() const {return age;}
T getWeight() const {return weight;}
//类模板中成员函数在类内的写法
Cml& operator+=(const Cml& ss)
{
this->age += ss.age;
this->weight += ss.weight;
return *this;
}
private:
T age, weight;
};
//成员函数在类外
template <class T>
Cml<T>& Cml<T>::operator+=(const Cml<T>& ss)
{
this->age += ss.age;
this->weight += ss.weight;
return * this;
}
//main函数调用
Cml<double> cml(80, 160);
Cml<double> cml1(-70, -50);
cml += cml1;
std::cout << cml.getAge() << endl;
//输出结果是10
相比之下,函数模板就比类模板简单许多:如下
template <class T>
class Cml
{
public:
Cml(T _age = 18, T _weight = 90): age(_age), weight(_weight){}
T getAge() const {return age;}
T getWeight() const {return weight;}
Cml& operator+=(const Cml& ss);
bool operator <(const Cml& ss) const {return age < ss.age;}//为下列的min函数服务
// {
// this->age += ss.age;
// this->weight += ss.weight;
// return *this;
// }
private:
T age, weight;
};
template <class T>
Cml<T>& Cml<T>::operator+=(const Cml<T>& ss)
{
this->age += ss.age;
this->weight += ss.weight;
return * this;
}
//函数模板
template <class T>//这个T与上面的T表达的意思不一样,名字可以随便起
inline const T& min(const T& a, const T& b)
{
return b < a ? b : a;
}
//先看main里的调用
Cml<double> cml(80, 160);
Cml<double> cml1(-70, -50);
cml += cml1;
std::cout << cml.getAge() << endl;
//以上是类模板,传递的T是double需要在类名后面表明
//而下面传递的是cml类型,,也就是Cml<double>类型,故而T是不一样的
//函数模板需要指定类型,编译器会对其进行实参推导,推导出T为Cml<T>故而调用operator<
Cml<double> a = min(cml, cml1);
cout << a.getAge() << endl;
//输出70
成员模板即在类里面再写模板template,从而实现特殊的效果,比如:
template <class T>
class Cml1 : public Cml<T>
{
template<class T1>
explicit Cml1(T1 _age, T1 _weight):Cml<T>(_age, _weight){}
};
//在main函数里就可以实现这样一种写法,技术Base是父类,dep是子类
Cml1<Base> ss = new dep(..., ...);//模拟up_cast
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。