C++ 如何在联合中构造结构?

C++ 如何在联合中构造结构?,c++,unions,C++,Unions,下面的t2导致以下编译错误 test.cpp:14:15: error: cannot initialize a member subobject of type 'E' with an rvalue of type 'int' Test t2{2, {{2, 3}}}; ^ test.cpp:14:18: error: cannot initialize a member subobject of type 'void *' with a

下面的t2导致以下编译错误

test.cpp:14:15: error: cannot initialize a member subobject of type 'E' with an rvalue of type 'int'
        Test t2{2, {{2, 3}}};
                    ^
test.cpp:14:18: error: cannot initialize a member subobject of type 'void *' with an rvalue of type 'int'
        Test t2{2, {{2, 3}}};
如何初始化第二个集合?如果我切换结构和联合,可能吗

enum E {
    ea, eb, ec
};
struct Test {
    int a;
    union {
        struct{E e; void*p; };
        struct{int b, c; };
    };
};

int main() {
    Test t1{1, {{ea, 0}}};
    Test t2{2, {{2, 3}}};
}

非常简单,只有
联合的第一个(非静态)成员可以用这种方式初始化。阅读更多:


C++和联合的正确实现相当复杂。用C++ 17,<代码> STD::变体< /C> >是您想要的解决方案。我认为C++中的匿名结构不是KoSH。可能有一些奇怪的行为,但是假设GCC,您可能会得到类似C的行为
int
转换为
enum
,将
int
转换为指针。没有演员阵容,两者都不合法。。这与UNIONE无关。@ USER481301 C++强制你将int类型转换成枚举,这样只有第二组兼容。此外,INT不会被丢进空白中,我会自动为不清楚而道歉。这正是我想表达的观点。林克看起来只是一点参考资料。下面是直接链接:旁注:如果C++20可用,您可以使用指定的初始值设定项。但不能使用匿名结构。由于匿名结构在起作用,我不能保证这个正确答案是正确的。这就是非标准扩展的痛苦。