100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 【c++】模板类继承模板类

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

时间:2019-06-12 09:28:24

相关推荐

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

C++继承访问权限:/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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。