gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:37:40 25 4
gpt4 key购买 nike

对于下面的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com