簡體   English   中英

C ++不能使用從基類繼承的getter函數

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM