5

Is there a way to force a derived class to use the constructor of the abstract base class? It must not be a real constructor, I have an open mind about creative solutions.

class Abstract
{
private:
    int Member;
    string Text;

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

    // e.g. defining virtual functions
}

For example my abstract class has some private members which every derived class should also have. And they should be defined in the constructor, even against the will of the derived class.

I am aware that constructors are not inherited. But is there a workaround to produce a similar behavior?

4

2 回答 2

18

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

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

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

class Derived : public Base
{
    using Base::Base; // <-- Brings to derived the Base's constructor.
};

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

于 2012-10-08T14:35:20.893 回答
9

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

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

class Derived : public Base
{
    Derived(int Member, string Text) : Base(Member, Text) {
                                    // ^^^^^^^^^^^^^^^^^^
        // ...
    }
};
于 2012-10-08T14:23:37.477 回答