繁体   English   中英

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

[英]Access protected members of base class in grandchild class

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

例如,如何在TooSmall类中访问width

考虑以下代码示例:

#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;
}

有没有一种方法可以使子类中的父类属性public

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

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);
};

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


如果出于某种原因,您想坚持私有继承,则必须将私有继承的受保护成员“提升”为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);
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM