Abh*_*agi 2 c++ inheritance access-specifier c++11 c++14
我有一个包含属性声明为的父类protected
。我知道protected
可以在子类中访问成员。但是如何在孙子类中访问相同内容。
例如,如何width
在TooSmall
课堂上访问?
考虑以下代码示例:
#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
中的父类属性?。
您的问题是您是从基类私有继承的,因此基类的公共成员和受保护成员与派生类的私有成员具有相同的访问控制。尽管可能,私有继承是一个非常特定的工具,很少使用。在大多数情况下,您需要公共继承:
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)