我可以从 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
相同。换句话说,Vehicle 是一个不会向 Sedan 用户公开的实现细节。要实现此公共(public)继承,您应该编写 class Sedan : public Vehicle
。
关于C++ 不能使用从基类继承的getter函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52070384/