[英]Can we access protected member functions of base class in derived class?
正如我研究過的那樣,派生類可以訪問基類的受保護成員。 在派生類中,基類的受保護成員在派生類中作為公共成員工作。 但是當我實現這個時,我得到一個錯誤
我的代碼:
#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) {
^~~~~~~~~
請有人幫我理解訪問修飾符
是的,派生類可以訪問受保護的成員,無論這些成員是數據還是函數。 但是在您的代碼中, main
是嘗試訪問setWidth
和setHeight
,而不是Rectangle
。 這是無效的,就像使用main
width
和height
一樣。
使用受保護成員函數的派生類示例:
class Rectangle: public Shape {
public:
int getArea() const {
return (width * height);
}
void setDimensions(int w, int h) {
setWidth(w);
setHeight(h);
}
};
或者,如果您真的希望Rectangle
讓其他任何人使用這些函數,您可以使用訪問Rectangle
必須使它們成為Rectangle
public
成員而不是protected
:
class Rectangle: public Shape {
public:
using Shape::setWidth;
using Shape::setHeight;
int getArea() const {
return (width * height);
}
};
在派生類中,基類的受保護成員在派生類中作為公共成員工作。
那不是真的。 要么您的來源是錯誤的,要么此引用脫離了相關上下文。
默認情況下,公共繼承基類的受保護成員在派生類中仍受保護,這意味着派生類成員函數可以訪問它們,但不能從類外部訪問它們。
您可以在此處確認並了解更多詳細信息,特別是在“受保護的成員訪問”段落中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.