让我在问题之前添加以下代码:
struct A
{
explicit A(int i):a_{i} {}
int a_
};
struct B
{
B():mya_{5} {} // Initialize mya_ (again?)
A mya_{7}; // Initialize mya_
};
在struct B
我们在 mya_
的类内初始值设定项之间存在冲突和 mya_
在 B
中初始化的构造函数的初始化列表。根据 C++ 标准如何解决这个问题,mya_.a_
的最终值应该是多少?什么时候B
搭建完成了吗?
最佳答案
初始化列表获胜。如果您有另一个不初始化成员的构造函数,就地初始化将获胜。
例如,
struct B
{
B():mya_{5} {}
B(int) {}
A mya_{7};
};
int main
{
B b0; // b.mya_.a_ is 5
B b(42); // b.mya_.a_ is 7
}
来自12.6.2 初始化基类和成员[class.base.init]
If a given non-static data member has both a brace-or-equal-initializer and a mem-initializer, the initialization specified by the mem-initializer is performed, and the non-static data member’s brace-or-equal-initializer is ignored. [ Example: Given
struct A {
int i = /∗ some integer expression with side effects ∗/ ;
A(int arg) : i(arg) { }
// ...
};
the A(int) constructor will simply initialize i to the value of arg, and the side effects in i’s brace-or-equal- initializer will not take place. — end example ]
关于c++ - 类内成员初始化器与初始化列表的冲突解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991180/