【问题标题】:Calling the constructor of a base class inside the constructor of its derived class C++ [duplicate]在其派生类C++的构造函数中调用基类的构造函数[重复]
【发布时间】:2017-12-12 04:19:44
【问题描述】:

我正在尝试编写一个将不同类型的蛋糕插入发票的程序,它使用了几个派生类。我想使用派生类的构造函数来初始化抽象父类中的一些数据成员。有没有办法可以做到这一点,以便我可以保持数据成员私有,并在派生类中调用基类构造函数来初始化它们?例如:

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;
};

【问题讨论】:

    标签: c++ inheritance constructor


    【解决方案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;
        }
        ...
    };
    

    【讨论】:

    • 如果我使用的是头文件,我是在声明和实现中都使用这种语法,还是只在实现中使用?
    • @Jake 只是实现。
    猜你喜欢
    • 2015-08-18
    • 2016-07-19
    • 2020-09-22
    • 2018-07-16
    • 2018-07-21
    • 2020-11-28
    • 1970-01-01
    • 2014-11-17
    • 2015-05-28
    相关资源
    最近更新 更多