【c++】模板类继承模板类

本文介绍了C++中的继承概念,包括普通类继承和模板类继承。通过示例代码展示了如何设置和使用继承的访问权限,以及在模板类中如何调用父类的数据和方法。内容涵盖了设置成员变量的保护级别、派生类访问基类成员以及模板类在继承中的特殊用法。
摘要由CSDN通过智能技术生成

C++继承访问权限:https://www.runoob.com/cplusplus/cpp-inheritance.html
在这里插入图片描述

1. 普通类继承

demo

 #include <iostream>

using namespace std;

// 基类
class Shape
{
public:
    void setWidth(int w)
    {
        width = w;
    }
    void setHeight(int h)
    {
        height = h;
    }

protected:
    int width;
    int height;
};

// 派生类
class Rectangle : public Shape
{
public:
    int getArea()
    {
        setHeight(-1);
        return (width * height);
    }
};

int main(void)
{
    Rectangle Rect;

    Rect.setWidth(5);
    Rect.setHeight(7);

    // 输出对象的面积
    cout << "Total area: " << Rect.getArea() << endl;

    return 0;
}

2. 模板类继承模板类

和普通继承的区别,在于子类使用父类数据和方法时需要加this->

#include <iostream>

using namespace std;

// 基类
template <class vertex_t, class value_t>
class Shape
{
public:
    void setWidth(int w)
    {
        width = w;
    }
    void setHeight(int h)
    {
        height = h;
    }

protected:
    int width;
    int height;
};

// 派生类
template <class vertex_t, class value_t>
class Rectangle : public Shape<vertex_t, value_t>
{
public:
    int getArea()
    {
        this->setHeight(-1); // 模板子类使用模板父类函数和变量需要用:this->
        return (this->width * this->height);
    }
};

int main(void)
{
    Rectangle<int, int> Rect;

    Rect.setWidth(5);
    Rect.setHeight(7);

    // 输出对象的面积
    cout << "Total area: " << Rect.getArea() << endl;

    return 0;
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ystraw_ah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值