[英]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.