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

标签 c++ visual-studio-2008 unions default-constructor standard-layout

对于下面的代码:

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 之前,您只能在 union 内使用 POD 类型,这意味着 MSVS 2008 会给出正确的错误。为了使用新类型的 union ,您需要获得支持该更改的 MSVS 版本。来自 this MSDN article我们可以在 Unrestricted unions 部分看到,直到 2015 版才进行了更改。

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

关于c++ - 联盟成员具有用户定义的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40088319/

相关文章:

c++ - 在 C++03 中通过 int 传输 double 是否安全?

c++ - 关于C++中 vector 、 union 和指针的问题

c++ - VS2017 和 VS2015 之间的链接器有区别吗?

c++ - C++如何在自定义容器中正确调用deallocate

c++ - 在某个类的析构函数中删除指向对象的指针会自动从堆中删除吗?

c++ - 链接器在同一目录中找不到静态库

visual-studio-2008 - 在 Visual Studio 2008 中更改字体大小和样式

visual-studio - 在 Windows 7 上安装 VS 2008 Team Developer

visual-studio - 如何在 Visual Studio 中获得 .cu 文件的语法突出显示?

c - 如何使用结构中的 union 访问 C 结构