5--从类模板派生类模板和非模板类

本文详细解释了如何在C++中使用类模板派生出非模板类,通过Rectangle和Square类的示例展示了模板参数的应用,以及如何正确继承和调用父类方法。
摘要由CSDN通过智能技术生成

 从类模板派生类模板的格式如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值