该变量front_wheel
没有被覆盖 - 它只是被隐藏了。成员变量Wheel front_wheel
仍在Mountainbike
类中。所以实际上有两个名为front_wheel
in的变量Mountainbike
。但是要访问隐藏的变量,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;
};
然后,您可以根据需要扩展 Bike:
class RegularBike: public Bike<Wheel> {
/* Special methods for regular bike...*/
};
class MtbBike: public Bike<MtbWheel> {
/* Special methods for Mtb bike...*/
};