簡體   English   中英

為什么具有類內初始化的 class 不能用作聯合的成員?

[英]Why a class with in-class initialization can't be used as member of a union?

我有以下代碼

#include <iostream>
using namespace std;

struct S{
    int a = 0;
    S() = default;
};

union U {
    S s;
    int i;
};

int main() {
    U u;
    u.s.a = 1;
    return 0;
}

但是,它無法編譯並發出以下錯誤

prog.cpp: In function ‘int main()’:
prog.cpp:15:4: error: use of deleted function ‘U::U()’
  U u;
    ^
prog.cpp:9:7: note: ‘U::U()’ is implicitly deleted because the default definition would be ill-formed:
 union U {
       ^
prog.cpp:10:4: error: union member ‘U::s’ with non-trivial ‘constexpr S::S()’
  S s;
    ^

但是,當我通過添加默認構造函數修改 U 的定義時,它會編譯.

union U {
    S s;
    int i;
    U() {
 
    }
};

我的問題是為什么沒有給定的默認構造函數代碼無法編譯? 我們在 C++ 標准中有什么可以解釋的嗎?

我的猜測是 C++ 如果聯合具有非平凡成員,則禁止隱式默認構造函數。 具有類內初始化成員的 class 是非常重要的。 我對嗎?

聯盟不能包含“非平凡的”成員:見這里 “瑣碎”意味着該成員不應對其構造函數執行任何操作。 將 a 設置為 0 是在做某事,因此 union 不能包含此成員。

您的工會有兩名成員。 在任何時候,兩個成員之一處於活動狀態,構造函數必須使其中一個成員處於活動狀態,但默認構造函數無法知道是哪一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM