如何对枚举使用匿名联合

How to use anonymous unions with enums?

本文关键字:枚举      更新时间:2023-10-16

当我使用匿名 union时,如何正确访问成员数据和枚举符号?匿名联合的全部意义就在于省略了一层层次结构,使源代码不那么粗糙。我可以通过使用类型名和成员名命名union来解决这个问题,但我不想这样做。

这是VS2012。令人惊讶的是,编译器不会接受它,但智能感知会接受它!

struct A
{
    struct C {
        enum {M,N,O} bar;
    } c;
    union {
        struct B {
            enum { X,Y,Z} foo;
        } b;
    };
};
void test(void) {
    A a;
    a.c.bar = A::C::M;  // this works
    a.b.foo = A::B::X;  // this doesn't
}

给出这些消息

1>test.cpp(85): error C3083: 'B': the symbol to the left of a '::' must be a type
1>test.cpp(85): error C2039: 'X' : is not a member of 'A'
1>          test.cpp(71) : see declaration of 'A'
1>test.cpp(85): error C2065: 'X' : undeclared identifier

理想情况下,我希望使用匿名/未命名结构(这在某些编译器中确实有效,即使我意识到它不是标准的c++)

struct A
{
    union {
        struct  {
            enum { X,Y,Z} foo;
            int x;
        } ;
        struct  {
            enum { M,N,O} bar;
            double m;
        } ;
    };
};
void test(void) {
    A a1;
    a1.bar = A::M;
    a1.x = 1;
    A a2;
    a2.foo = A::X;
    a2.m = 3.14;
}

如果我正确理解你的问题,这应该工作:

struct A
{
    struct B {
        enum { X,Y,Z} foo;
        int x;
    };
    struct C {
        enum { M,N,O} bar;
        double m;
    };
    union {
        B b;
        C c;
    };
};