强制派生类使用基类的构造函数

dan*_*jar 4 c++ oop inheritance constructor class

有没有办法强制派生类使用抽象基类的构造函数?它绝不是真正的构造者,我对创造性解决方案持开放态度.

class Abstract
{
private:
    int Member;
    string Text;

public:
    Abstract(int Member, string Text)
    {
        this->Member = Member; 
        this->Text = Text;
    }

    // e.g. defining virtual functions
}
Run Code Online (Sandbox Code Playgroud)

例如,我的抽象类有一些私有成员,每个派生类也应该有.它们应该在构造函数中定义,甚至违背派生类的意愿.

我知道构造函数不是继承的.但有没有一种解决方法可以产生类似的行为?

Pap*_*ter 11

正如其他用户所建议的那样,必须将基类构造函数调用到派生类构造函数的初始化列表中.

但是C++ 11还有另一个很酷的解决方案:继承的构造函数:

class Base
{
    Base(int Member, string Text) { };
};

class Derived : public Base
{
    using Base::Base; // <-- Brings to derived the Base's constructor.
};
Run Code Online (Sandbox Code Playgroud)

但您必须确保您的编译器可以使用C++ 11功能; 当然,研究继承的构造函数是否符合您的要求而不仅仅因为它很酷而使用它.


tim*_*rau 7

使用派生类的构造函数的初始化列表.

class Base
{
    Base(int Member, string Text) { //...
    }
};

class Derived : public Base
{
    Derived(int Member, string Text) : Base(Member, Text) {
                                    // ^^^^^^^^^^^^^^^^^^
        // ...
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 这是一个有效的评论,但我不认为它回答了OP的问题. (3认同)
  • @KonradRudolph的问题是"*有没有办法迫使派生类中使用抽象基类的构造函数*?"这果然强制使用基类构造函数的. (3认同)