请考虑以下代码段:
#include <iostream> union U{ U(): i(1) {} int i; int j = 2; // this default member initializer is ignored by the compiler }; U u; int main(){ std::cout << u.i << '\n'; std::cout << u.j << '\n'; }
代码打印(见live example):
1 1
标准中的哪个地方说,编译器忽略成员U :: j的默认成员初始化器?
请注意,下面的联合不编译,这可以根据[class.union.anon]/4.我期待上面的代码段也不编译.
union U{ int i = 1; int j = 2; };
解决方法
Where in the Standard does it say that the default member initializer for the member U::j is ignored by the compiler?
请参阅C 17 CD中的[class.base.init]第9段子弹9.1.
注:您的演示具有未定义的行为,因为联盟的活动成员是我,但是您从j读取.这适用于一些编译器作为非标准扩展,但ISO C中不允许.