且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在派生类的构造函数中初始化没有默认构造函数的基类

更新时间:2022-11-23 18:17:39

因为您没有默认构造函数,编译器会抱怨它无法创建对象 primary ,你应该在 secondary 构造函数中添加一个参数/给它一个默认值:

Because you don't have a default constructor the compiler complains that it can't create an object for primary, you should either add a parameter to the secondary constructor / give it a default value:

class secondary : public primary
{
    public:
        secondary(int x);
        virtual ~secondary();
    protected:
    private:
};

然后调用基类构造函数:

And then call the base class constructor:

secondary::secondary(int x) : primary(x)
{
    //ctor
}

或者:

secondary::secondary() : primary(5)
{
    //ctor
}

或者只为主要添加默认构造函数:

Or just add a default constructor for primary:

class primary
{
    public:
        primary(int x);
        primary() : primary_x(0) {}
        virtual ~primary();
    protected:
    private:
        int primary_x;
};