我们可以在派生类中访问基类的受保护成员函数吗?

Tus*_*ain 0 c++ inheritance derived radix

据我研究,派生类可以访问基类的受保护成员。在派生类中,基类的受保护成员在派生类中作为公共成员。但是当我实现这个时,我得到一个错误

\n

我的代码:

\n
\n#include <iostream>\n \nusing namespace std;\n\nclass Shape {\n   protected :\n      void setWidth(int w) {\n         width = w;\n      }\n      void setHeight(int h) {\n         height = h;\n      }\n      \n   protected:\n      int width;\n      int height;\n};\n\n// Derived class\nclass Rectangle: public Shape {\n   public:\n      int getArea() { \n         return (width * height); \n      }\n};\n\nint main(void) {\n   Rectangle Rect;\n \n   Rect.setWidth(5);\n   Rect.setHeight(7);\n\n   // Print the area of the object.\n   cout << "Total area: " << Rect.getArea() << endl;\n\n   return 0;\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

错误 :

\n
In function \xe2\x80\x98int main()\xe2\x80\x99:\n32:19: error: \xe2\x80\x98void Shape::setWidth(int)\xe2\x80\x99 is protected within this context\n    Rect.setWidth(5);\n                   ^\n\n:9:12: note: declared protected here\n       void setWidth(int w) {\n            ^~~~~~~~\n:33:20: error: \xe2\x80\x98void Shape::setHeight(int)\xe2\x80\x99 is protected within this context\n    Rect.setHeight(7);\n                    ^\n:12:12: note: declared protected here\n       void setHeight(int h) {\n            ^~~~~~~~~\n\n\n
Run Code Online (Sandbox Code Playgroud)\n

请有人帮助我理解访问修饰符

\n

asc*_*ler 5

是的,派生类可以访问受保护的成员,无论这些成员是数据还是函数。但在您的代码中,它main正在尝试访问setWidthand setHeight,而不是Rectangle。就像使用widthand heightfrom一样,这是无效的main

使用受保护成员函数的派生类的示例:

class Rectangle: public Shape {
public:
    int getArea() const { 
        return (width * height); 
    }
    void setDimensions(int w, int h) {
        setWidth(w);
        setHeight(h);
    }
};
Run Code Online (Sandbox Code Playgroud)

或者,如果您确实想让Rectangle其他人使用这些功能,您可以使用 access Rectanglehas 使它们成为public成员,Rectangle而不是protected

class Rectangle: public Shape {
public:
    using Shape::setWidth;
    using Shape::setHeight;

    int getArea() const { 
        return (width * height); 
    }
};
Run Code Online (Sandbox Code Playgroud)