构造函数初始值设定项列表不遵循顺序 [英] Constructor initializer list doesn't follow order

查看:68
本文介绍了构造函数初始值设定项列表不遵循顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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;

我希望输出为:基本构造函数,测试:50",但事实并非如此,因为 Base 构造函数在 variable 已初始化,没有错误也没有警告,它只是编译.

And I would expect that output would be: "Base constructor, test: 50", but that isn't the case, because Base constructor gets called before variable is initialized, there is no error nor warning, it just compiles.

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

Is there any way i can make Base constructor get called after ? Or is this generally bad design ?

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

I'm tryting to get rid of all the init methods and their calls by putting them into constructor insted, this behavior stop me from doing that.

推荐答案

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

Is there any way i can make Base constructor get called after?

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

No. An object's constructor must construct its base classes before any named member variables.

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

I'm trying to get rid of all the init methods and their calls by putting them into constructor instead

这是值得的努力!

我假设您的真实代码 变量 int 更复杂.因为如果是整数,则只需调用 Base(50).

I'll assume your real code variable is something more complex than an int. Because if it's an int, you could simply call Base(50).

您可以使用 延迟构造器 在任何构造函数开始初始化之前准备变量.

You can use delagating constructors to prepare a variable before any constructor begins initialization.

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;

};

这篇关于构造函数初始值设定项列表不遵循顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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