联盟成员具有用户定义的构造函数

Member of Union has User-Defined Constructor

对于以下代码:

class Foo{
    int foo;
public:
    Foo() : foo(13) {}
    int getFoo() const { return foo; }
};

union Bar{
    Foo fBar;
    double dBar;
};

我相信这在 C++ 中是完全合法的。 http://en.cppreference.com/w/cpp/language/union#Explanation 说:

If two union members are standard-layout types, it's well-defined to examine their common subsequence on any compiler

因此 in gcc I can do this:

Bar bar = { Foo() }

当我在 Visual Studio 2008 年尝试此操作时,出现错误:

error C2620: member Bar::fBar of union Bar has user-defined constructor or non-trivial default constructor

Error C2620 状态:

A union member cannot have a default constructor.

这是怎么回事?这是 C++ 的要求吗,我认为标准布局是唯一的要求?有解决办法吗?

在 C++98/03 中,9.5 中规定的 C++ 标准

[...]If a POD-union contains several POD-structs that share a common initial sequence (9.2), and if an object of this POD-union type contains one of the POD-structs, it is permitted to inspect the common initial sequence of any of POD-struct members;[...]

这在 C++11 中更改为

[...]If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members;[...]

所以在 C++11 之前,您只能在联合中使用 POD 类型,这意味着 MSVS 2008 会给出正确的错误。为了使用新类型的联合,您需要获得支持该更改的 MSVS 版本。从 this MSDN article 我们可以在 Unrestricted unions 部分看到该更改直到 2015 版才进行。

您要么必须升级,要么将 class 更改为 POD type