【问题标题】:Can we access protected member functions of base class in derived class?我们可以在派生类中访问基类的受保护成员函数吗?
【发布时间】: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


【解决方案1】:

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

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

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

或者如果你真的想让Rectangle 让其他人使用这些功能,你可以使用访问权限Rectangle 必须让他们public 成为Rectangle 的成员,而不是protected

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

    int getArea() const { 
        return (width * height); 
    }
};

【讨论】:

    【解决方案2】:

    在派生类中,基类的受保护成员在派生类中作为公共成员。

    那不是真的。要么您的来源有误,要么此引文脱离了相关上下文。

    默认情况下,公共继承基类的受保护成员在派生类中仍然受到保护,这意味着派生类成员函数可以访问它们,但不能从类外部访问它们。

    您可以确认并了解更多详细信息here,特别是在“受保护的成员访问”段落中。

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 2022-07-20
      • 2014-08-27
      • 1970-01-01
      • 2019-01-20
      • 2012-08-29
      • 2018-11-27
      相关资源
      最近更新 更多