【发布时间】:2020-12-24 10:30:55
【问题描述】:
正如我所研究的,派生类可以访问基类的受保护成员。在派生类中,基类的受保护成员在派生类中作为公共成员。但是当我实现这个时,我得到一个错误
我的代码:
#include <iostream>
using namespace std;
class Shape {
protected :
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
错误:
In function ‘int main()’:
32:19: error: ‘void Shape::setWidth(int)’ is protected within this context
Rect.setWidth(5);
^
:9:12: note: declared protected here
void setWidth(int w) {
^~~~~~~~
:33:20: error: ‘void Shape::setHeight(int)’ is protected within this context
Rect.setHeight(7);
^
:12:12: note: declared protected here
void setHeight(int h) {
^~~~~~~~~
请有人帮我理解访问修饰符
【问题讨论】:
-
Rectangle::setWidth()不是public,但您正试图像这样访问它。
标签: c++ inheritance base derived