如何解决我们可以访问派生类中基类的受保护成员函数吗?
正如我研究的那样,派生类可以访问基类的受保护成员。在派生类中,基类的受保护成员在派生类中作为公共成员工作。但是,当我实现此方法时,会出现错误
我的代码:
#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) {
^~~~~~~~~
请有人帮助我了解Access修饰符
解决方法
是的,派生类可以访问受保护的成员,无论这些成员是数据还是函数。但是在您的代码中,main
试图访问setWidth
和setHeight
,而不是Rectangle
。就像使用width
中的height
和main
一样无效。
使用受保护成员函数的派生类的示例:
class Rectangle: public Shape {
public:
int getArea() const {
return (width * height);
}
void setDimensions(int w,int h) {
setWidth(w);
setHeight(h);
}
};
或者,如果您确实希望Rectangle
允许其他人使用这些功能,则可以使用访问权限Rectangle
使其成为public
的{{1}}成员,而不是{ {1}}:
Rectangle
,
在派生类中,基类的受保护成员在派生类中充当公共类。
那是不对的。或者您的来源有误,或者该引用是出于相关上下文。
默认情况下,公共继承基类的受保护成员在派生类中仍受保护,这意味着派生类成员函数可以访问它们,但不能从类外部访问它们。
您可以确认它并了解更多详细信息here,特别是在“受保护的成员访问权限”段落中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。