600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 【C++】not accessible because 'Rectangle' uses 'private' to inherit from 'Shape'

【C++】not accessible because 'Rectangle' uses 'private' to inherit from 'Shape'

时间:2020-12-15 04:59:02

相关推荐

【C++】not accessible because 'Rectangle' uses 'private' to inherit from 'Shape'

1、错误代码

#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: Shape{public:int getArea(){ return (width * height); }};int main(void){Rectangle Rect;Rect.setWidth(5);Rect.setHeight(7);cout << "Total area: " << Rect.getArea() << endl;return 0;}

提示错误如下:

2、由于派生类继承基类时“class Rectangle: Shape”,缺少public,导致的问题,修改如下:

#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(){ return (width * height); }};int main(void){Rectangle Rect;Rect.setWidth(5);Rect.setHeight(7);cout << "Total area: " << Rect.getArea() << endl;return 0;}

正确输出如下:

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