變量front_wheel
未被覆蓋 - 它只是隱藏。成員變量Wheel front_wheel
仍處於Mountainbike
類中。所以實際上在Mountainbike
中有兩個變量front_wheel
。但要訪問Mountainbike
中的隱藏變量,您需要明確說明:Bike::front_wheel
。
做你想要什麼更好的辦法是不帶數據創建一個接口類:
class Bike {
public:
virtual Wheel const &getFronWheel() const = 0;
virtual ~Bike() {}
};
,然後得出與任何特定摩托:
class RegularBike: public Bike {
public:
virtual Wheel const &getFronWheel() const { return wheel; }
private:
Wheel wheel;
}
class MtbBike: public Bike {
public:
virtual MtbWheel const &getFronWheel() const { return wheel; }
private:
MtbWheel wheel;
}
編輯:沒有使用虛擬,但模板,而不是:
template<typename WheelType>
class Bike {
public:
/* Common methods for any bike...*/
protected: // or private
WheelType wheel;
};
然後你願意,你可以延長自行車:
class RegularBike: public Bike<Wheel> {
/* Special methods for regular bike...*/
};
class MtbBike: public Bike<MtbWheel> {
/* Special methods for Mtb bike...*/
};
你不是在重寫''front_wheel'',你隱藏了''front_wheel''的名字。 – juanchopanza
您不能覆蓋成員對象。 –
「Softwaretechnically」必須是來自TeutoniC++的術語:-) –