![](/img/trans.png)
[英]C++ Class function inheritance using variable of another class that is inherited from base class
[英]C++ Cannot use getter function inherited from base class
我可以从Sedan
类中访问Vehicle::color
的唯一方法是重新实现getter方法。 我想从子类访问它,而不这样做。
// Base Class
class Vehicle
{
protected:
bool windowIsOpen[4];
int wheels;
char *color;
public:
Vehicle(char *color) : color(color){};
char *getColor() { return color; }
};
class Sedan : Vehicle
{
public:
Sedan(char* color) : Vehicle(color) {}
};
int main(int argc, char **argv){
Sedan se("green");
cout<<se.getColor()<<endl;
return 0;
}
在定义类时,您编写了class Sedan : Vehicle
。 这实际上与class Sedan : private Vehicle
相同class Sedan : private Vehicle
。 换句话说,Vehicle是一个不向Sedan用户公开的实现细节。 要进行此公共继承,您应该编写class Sedan : public Vehicle
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.