构造函数初始值设定项列表不遵循顺序

时间:2021-04-15 14:54:49

标签: c++ constructor derived-class

我有以下代码:

class Base
{
public:
    Base(int test) { std::cout << "Base constructor, test: " << test << std::endl; }
};

class Derived : public Base
{
private:
    int variable;

public:
    Derived() :
        variable(50),
        Base(variable)
    {}
};

Derived derived;

我希望输出是:“Base constructor, test: 50”,但事实并非如此,因为在初始化 Base 之前调用了 variable 构造函数,没有错误或警告,它只是编译。

有什么办法可以让 Base 构造函数在之后被调用?或者这通常是糟糕的设计?

我试图通过将它们放入构造函数中来摆脱所有 init 方法及其调用,这种行为阻止我这样做。

1 个答案:

答案 0 :(得分:5)

<块引用>

有什么办法可以让 Base 构造函数在之后被调用吗?

没有。对象的构造函数必须在任何命名成员变量之前构造其基类。

<块引用>

我试图通过将它们放入构造函数来摆脱所有 init 方法及其调用

这是一项值得的努力!

我假设您的真实代码 variableint 更复杂。因为如果它是一个 int,你可以简单地调用 Base(50)

您可以使用 delagating constructors 在任何构造函数开始初始化之前准备一个变量。

class Derived : public Base
{
public:
    // Generate an important value FIRST, and then delegate
    // construction to a new constructor.
    Derived() : Derived( GenerateSomethingComplex() ) {}

private:

    // Here, we can honor constructing Base before Derived
    // while "some value" has been procured in advance.
    Derived( SomethingComplex&& var) :
        Base( var ),
        variable( std::move(var) )
    {}

    SomethingComplex variable;

};