联盟成员具有用户定义的构造函数 [英] Member of Union has User-Defined Constructor

查看:23
本文介绍了联盟成员具有用户定义的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码:

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 说:

I believe this is fully legal in C++. http://en.cppreference.com/w/cpp/language/union#Explanation says:

如果两个联合成员是标准布局类型,则在任何编译器上检查它们的公共子序列都是明确定义的

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

因此在gcc中我可以做到这一点:

Bar bar = { Foo() }

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

When I try this in Visual Studio 2008 I get the error:

错误 C2620:union Bar 的成员 Bar::fBar 具有用户定义的构造函数或非平凡的默认构造函数

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

错误 C2620 指出:

联合成员不能有默认构造函数.

A union member cannot have a default constructor.

这是怎么回事?这是否曾经是 C++ 的要求,我认为标准布局是唯一的要求?有没有办法解决这个问题?

What's going on here? Was this ever a C++ requirement, I thought that Standard Layout was the only requirement? Is there a work around for this?

推荐答案

在 C++98/03 中,C++ 标准在 9.5 中声明

In C++98/03 the C++ standard stated in 9.5

[...]如果一个 POD-union 包含多个 POD-structs,它们共享一个共同的初始序列 (9.2),并且如果这个 POD-union 类型的对象包含一个 POD-structs,它被允许检查任何 POD-struct 成员的公共初始序列;[...]

[...]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 中被更改为

And this was changed in C++11 to

[...]如果一个标准布局联合包含多个标准布局结构,它们共享一个共同的初始序列(9.2),并且如果这个标准布局联合类型的对象包含标准布局结构之一,允许检查任何标准布局结构成员的公共初始序列;[...]

[...]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 版本.从 这篇 MSDN 文章,我们可以在 部分下看到不受限制的工会表示,直到 2015 年版本才进行了更改.

So before C++11 you could only use a POD type inside a union which means MSVS 2008 is giving you the right error. In order to use the new type of union you need to get the version of MSVS that supports that change. From this MSDN article we can see under the section for Unrestricted unions that that change was not made until version 2015.

您要么必须升级,要么将类更改为 POD 类型

You are either going to have to upgrade or change the class to be a POD type

这篇关于联盟成员具有用户定义的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆