访问孙类中受保护的基类成员

Abh*_*agi 2 c++ inheritance access-specifier c++11 c++14

我有一个包含属性声明为的父类protected。我知道protected可以在子类中访问成员。但是如何在孙子类中访问相同内容。

例如,如何widthTooSmall课堂上访问?

考虑以下代码示例:

#include <iostream>
using namespace std;

class Box {
   protected:
      double width;
};

class SmallBox:Box {
   protected:
      double height;
};

class TooSmall:SmallBox {
    public:
        void setSmallWidth( double wid );
        void setHeight(double hei);
        double getSmallWidth( void );
        double getHeight(void);
};


double TooSmall::getSmallWidth(void) {
   return width ;
}

void TooSmall::setSmallWidth( double wid ) {
   width = wid;
}

void TooSmall::setHeight( double hei ) {
   height = hei;
}

double TooSmall::getHeight(void) {
   return height;
}

// Main function for the program
int main() {
   TooSmall box;

   box.setSmallWidth(5.0);
   box.setHeight(4.0);
   cout << "Width of box : "<< box.getSmallWidth() << endl;
   cout << "Height of box : "<< box.getHeight() << endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使子类public中的父类属性?

Rei*_*ica 5

您的问题是您是从基类私有继承的,因此基类的公共成员和受保护成员与派生类的私有成员具有相同的访问控制。尽管可能,私有继承是一个非常特定的工具,很少使用。在大多数情况下,您需要公共继承:

class SmallBox: public Box {
   protected:
      double height;
};

class TooSmall: public SmallBox {
    public:
        void setSmallWidth( double wid );
        void setHeight(double hei);
        double getSmallWidth( void );
        double getHeight(void);
};
Run Code Online (Sandbox Code Playgroud)

这样,受保护的成员将对所有后代(不仅是直系子代)正常可见。


如果出于某种原因,您想坚持私有继承,则必须将私有继承的受保护成员“提升”为protected:

class SmallBox:Box {
   protected:
      double height;
      using Box::width; // make it protected again
};

class TooSmall:SmallBox {
    public:
        void setSmallWidth( double wid );
        void setHeight(double hei);
        double getSmallWidth( void );
        double getHeight(void);
};
Run Code Online (Sandbox Code Playgroud)

  • @AbhinavKinagi答案已更新。但是,请仔细检查私有继承确实是您想要的。公共继承代表了标准,这是人们在谈到继承时通常期望的一种关系。另一方面,受保护的/私有的继承代表了术语的实现,并且从某些角度来看,它更接近于组合而不是实际的继承。 (3认同)