可以使用成员变量在初始化列表中初始化其他成员吗?
考虑以下(简化的)情况:
class Foo
{
private:
int evenA;
int evenB;
int evenSum;
public:
Foo(int a, int b) : evenA(a-(a%2)), evenB(b-(b%2)), evenSum(evenA+evenB)
{
}
};
当我这样实施foo时:
Foo foo(1,3);
然后偶数为0,偶数为2,但是evensum是否会初始化为2?
我在当前平台(iOS)上尝试了此操作,但它似乎有效,但是我不确定此代码是否可移植。
感谢您的帮助!
Consider the following (simplified) situation:
class Foo
{
private:
int evenA;
int evenB;
int evenSum;
public:
Foo(int a, int b) : evenA(a-(a%2)), evenB(b-(b%2)), evenSum(evenA+evenB)
{
}
};
When i instanciate Foo like this:
Foo foo(1,3);
then evenA is 0, evenB is 2, but will evenSum be initialized to 2?
I tried this on my current platform (iOS) and it seems to work, but I'm not sure whether this code is portable.
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
此是 良好的便携式, 1 ,但可能容易出错。
成员按在班级正文中声明的顺序初始化,而不是初始化列表中列出的顺序。因此,如果您更改班级主体,则此代码可能会默默失败(尽管许多编译器会发现这一点并发出警告)。
1. From [class.base.init] in the C++ standard(s):
(突出显示是我的。)
随后,标准的这一部分继续提供一个使用成员变量来初始化其他成员变量的示例。
This is well-defined and portable,1 but it's potentially error-prone.
Members are initialized in the order they're declared in the class body, not the order they're listed in the initialization list. So if you change the class body, this code may silently fail (although many compilers will spot this and emit a warning).
1. From [class.base.init] in the C++ standard(s):
(Highlighting is mine.)
This section of the standard then goes on to give an example of using member variables to initialize other member variables.
是的,提供它们已经建成。只是不要忘记
施工顺序是声明的顺序
班级定义,不是在
构造函数。而且编译器通常不会告诉您是否使用
在构造它之前。例如,在您的情况下,
如果您将
evensum
移动到班级的顶部,则您的未定义行为(因为其初始化器使用非初始化的成员),甚至
尽管在构造函数中,您可以初始化
evena
和evenb
词汇evensum
之前。Yes, provide they've already been constructed. Just don't forget
that the order of construction is the order of the declarations in the
class definition, not the order of the initializers in the
constructor. And that the compiler typically won't tell you if you use
a variable before it has been constructed. In your case, for example,
if you move
evenSum
to the top of the class, you have undefinedbehavior (because its initializer uses uninitialized members), even
though in your constructor, you initialize
evenA
andevenB
lexicallybefore
evenSum
.成员按在类定义中声明的顺序初始化。只要您的初始化列表遵循此订单,就可以了。
Members are initialized in the order they're declared in the class definition. As long as your initializer list follows this order, it should be ok.
调用初始化器的顺序:
初始化顺序
,所以是的,只要
evena
andevenb
在evensum
之前声明 evenbThe order in which initializers are called:
Initialization order
So yes, your example will work, as long as
evenA
andevenB
are declared beforeevenSum
这也在G ++ 4.0.3(现在6岁)上进行了编译。
我有信心在任何合理的编译器上都可以纠正。
This also compiled without error on g++ 4.0.3 (6 years old now).
I feel confident this will compile fine on any reasonably recent compiler.