我正在尝试编写一个程序,将不同类型的蛋糕插入发票中,并使用多个派生类。我想使用派生类的构造函数来初始化抽象父类中的一些数据成员。有没有办法,我可以这样做,所以我可以保持数据成员私有,并在派生类内,调用基类构造函数初始化它们?例如:
class Cake:
public:
Cake(string flavor, string frosting) {
cakeType = flavor;
frostingType = frosting;
}
private:
string cakeType;
string frostingType;
};
class LayerCake: public Cake {
public:
LayerCake(string flavor, string frosting, int layers, int
quantity) {
numLayers = layers;
cakeQuantity = quantity;
Cake(flavor, frosting);
private:
int numLayers;
int cakeQuantity;
};
答案 0 :(得分:1)
在构造函数体内,Cake(flavor, frosting);
只构造一个临时的Cake
,它与派生类的基类子对象无关。
你想要的是member initializer list,例如
class LayerCake: public Cake {
public:
LayerCake(string flavor, string frosting, int layers, int
quantity) : Cake(flavor, frosting) {
// ~~~~~~~~~~~~~~~~~~~~~~~~
numLayers = layers;
cakeQuantity = quantity;
}
...
};