强制派生类使用基类的构造函数 [英] Force a Derived Class to use the Constructor of the Base Class

查看:124
本文介绍了强制派生类使用基类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法强制派生类使用抽象基类的构造函数?它不能是一个真正的构造函数,我对于创造性的解决方案有一个开放的心态。

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?

推荐答案

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

Use initializer list of the derived class' constructor.

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

class Derived : public Base
{
    Derived(int Member, string Text) : Base(Member, Text) {
                                    // ^^^^^^^^^^^^^^^^^^
        // ...
    }
};

这篇关于强制派生类使用基类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆