简体   繁体   English

C ++不能使用从基类继承的getter函数

[英]C++ Cannot use getter function inherited from base class

The only way I can access Vehicle::color from within Sedan class, is by reimplementing the getter method. 我可以从Sedan类中访问Vehicle::color的唯一方法是重新实现getter方法。 I want to access it from the subclass, without doing so. 我想从子类访问它,而不这样做。

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

When defining your class, you wrote class Sedan : Vehicle . 在定义类时,您编写了class Sedan : Vehicle This is effectively the same as class Sedan : private Vehicle . 这实际上与class Sedan : private Vehicle相同class Sedan : private Vehicle In other words, Vehicle is an implementation detail that ain't exposed to users of Sedan. 换句话说,Vehicle是一个不向Sedan用户公开的实现细节。 To make this public inheritance, you should write class Sedan : public Vehicle . 要进行此公共继承,您应该编写class Sedan : public Vehicle

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

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