从类模板派生类模板的格式如下:
template<typename T>
class Base
{
...
};
template<typename T>
class Derived :public Base<T>
{
...
};
举个例子:正方形是长方形的子类
代码如下:
#include<iostream>
using namespace std;
template<typename T>
class Rectangle //长方形
{
public:
//构造
Rectangle(T len, T wide) :m_len(len), m_wide(wide)
{ }
T circumference() const//周长
{
return (m_len + m_wide) * 2;
}
T area() const//面积
{
return m_len * m_wide;
}
//输出
void show() const
{
cout << "长=" << m_len << ",宽=" << m_wide << endl;
}
private:
T m_len;//长
T m_wide;//宽
};
//按照一般来写下面代码是有问题的,要加个类型说明<T>
//template<typename T>
//class Square :public Rectangle
//{
//public:
// Square(T len) :Rectangle(len, len)
// {
//
// }
//};
//下面是正确的代码
template<typename T>
class Square :public Rectangle<T> //正方形继承长方形
{
public:
//继承父类的构造函数
Square(T len) :Rectangle<T>(len, len)
{}
};
int main()
{
Square<int> sq1{ 10 };
sq1.show();
cout << "周长=" << sq1.circumference() << ",面积=" << sq1.area() << endl;
cout << endl;
Square<double>sq2{ 12.5 };
sq2.show();
cout << "周长=" << sq2.circumference() << ",面积=" << sq2.area() << endl;
return 0;
}
从类模板派生非模板类只需将正方形继承以及主函数做相应的修改就可以,代码如下:
class Square :public Rectangle<int> //正方形继承长方形
{
public:
//继承父类的构造函数
Square(int len) :Rectangle(len, len)
{}
};
int main()
{
Square sq1{ 20 };
sq1.show();
cout << "周长=" << sq1.circumference() << ",面积=" << sq1.area() << endl;
cout << endl;
return 0;
}