C++ Union/Struct 'printColorPicker::printColorPicker(void)': 试图引用已删除的函数

C++ Union/Struct 'printColorPicker::printColorPicker(void)': attempting to reference a deleted function

你好无情的社区,今天我希望得到你的帮助。

请看菜鸟代码

错误在第 20 行(我会评论它以便您看到)。

错误:'printColorPicker::printColorPicker(void)':试图引用已删除的函数

    #include <iostream>

    using namespace std;

    enum availableColors {
        incolorPrint,
        colorPrint
    };

    union printColorPicker {
        struct incolorPrint {
            int id; 
            char* details = "No color ink eh?";
        } i;

        struct colorPrint{
            int id;
            char* details = "Unicorn mode on";
        } c;
    } color; //line 20


    void colorPicker(availableColors c){
        char* option;

        switch (c) {
        case incolorPrint: {
            option = color.i.details;
        }
        break;

        case colorPrint: {
            option = color.c.details;
        } 
        break;
        }


        cout << option;
    }



    void main(){      
        colorPicker(colorPrint);
    }

我想做的是使用颜色选择器方法 echo/cout/printf printColorPicker 联合内的结构 (colorPrint,incolorPrint) 内的字符串。

我收到上述错误。

我不太了解 union 的疯狂,但很可能发生的情况是,当您为 details 提供默认值时,您实际上是在提供默认构造函数。 发生这种情况时,struct 不再是聚合类型,也称为 POD。这种非聚合性传播通过,并且联合也不再是聚合类型,然后在构造时调用已删除的默认构造函数。 (聚合类型在构造时不调用构造函数,其行为与 C 对象完全一样。)

编辑 union 仅要求其成员可简单构造。通过提供默认值,struct 将不再是微不足道的构造。聚合类型的区别是 private/protected 成员是允许的。

解决此问题的方法是删除 details 的默认值并在构建后分配给它们,可能是通过工厂函数。

顺便说一下,为一个 union 的不同对象设置默认值没有意义,应该设置哪个值?