简体   繁体   English

工会会员有用户定义的构造函数

[英]Member of Union has User-Defined Constructor

For the following code: 对于以下代码:

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

union Bar{
    Foo fBar;
    double dBar;
};

I believe this is fully legal in C++. 我相信这在C ++中是完全合法的。 http://en.cppreference.com/w/cpp/language/union#Explanation says: 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 如果两个联合成员是标准布局类型,则在任何编译器上检查它们的公共子序列是明确定义的

And thus in gcc I can do this : 因此, 在gcc中,我可以这样做

Bar bar = { Foo() }

When I try this in Visual Studio 2008 I get the error: 当我在Visual Studio 2008中尝试此操作时,出现错误:

error C2620: member Bar::fBar of union Bar has user-defined constructor or non-trivial default constructor 错误C2620: union Bar成员Bar::fBar具有用户定义的构造函数或非平凡的默认构造函数

Error C2620 states: 错误C2620指出:

A union member cannot have a default constructor. 联合成员不能具有默认构造函数。

What's going on here? 这里发生了什么? Was this ever a C++ requirement, I thought that Standard Layout was the only requirement? 这是否曾经是C ++的要求,我认为标准布局是唯一的要求? Is there a work around for this? 有没有解决的办法?

In C++98/03 the C++ standard stated in 9.5 在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;[...] [...]如果POD联合包含几个共享共同初始序列(9.2)的POD结构,并且如果此POD联合类型的对象包含其中一个POD结构,则可以检查公共任何POD结构成员的初始序列; [...]

And this was changed in C++11 to 并将其在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;[...] [...]如果一个标准布局联合包含多个共享公共初始序列(9.2)的标准布局结构,并且如果此标准布局联合类型的对象包含一个标准布局结构,则允许检查任何标准布局结构成员的公共初始序列; [...]

So before C++11 you could only use a POD type inside a union which means MSVS 2008 is giving you the right error. 因此,在C ++ 11之前,您只能在联合体内使用POD类型,这意味着MSVS 2008会为您提供正确的错误。 In order to use the new type of union you need to get the version of MSVS that supports that change. 为了使用新的联合类型,您需要获取支持该更改的MSVS版本。 From this MSDN article we can see under the section for Unrestricted unions that that change was not made until version 2015. 从此MSDN文章中,我们可以在“ 不受限制的联合 ”部分下看到,直到2015年才进行此更改。

You are either going to have to upgrade or change the class to be a POD type 您将不得不升级或将类更改为POD类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM