gpt4 book ai didi

c++ - 编译时错误: Union default constructor is deleted

转载 作者:行者123 更新时间:2023-12-02 10:58:05 28 4
gpt4 key购买 nike

以下C++代码无法编译。就我研究此问​​题而言,我知道该问题是因为联合的默认构造函数已被编译器删除。在线注释中指出:

If a union contains a non-static data member with a non-trivial default constructor, the default constructor of the union is deleted by default unless a variant member of the union has a default member initializer.


struct A {
int val;
A() : val(0) {}
};

union B
{
A a;
};

B b;

为什么将struct A的默认构造函数视为不平凡的?如何解决此问题以使此代码成功编译?

最佳答案

Why is the default constructor of struct A considered non-trivial?



因为它是用户声明的。

确实具有简单构造函数的类的示例:
struct Trivial {
int val;
};

struct Trivial2 {
int val;
Trivial2() = default;
};

作为奖励,这是不平凡的:
struct NonTrivial {
int val;
NonTrivial();
};
NonTrivial::NonTrivial = default;

但是,如果希望 A::val初始化为零,则需要向联合添加默认成员初始化器:
union B {
A a = {};
};

关于c++ - 编译时错误: Union default constructor is deleted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54504322/

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