简体   繁体   中英

How to use anonymous unions with enums?

How does one properly access the member data and enum symbols when I use an anonymous union ? The whole point of the anonymous union was so leave out one level of hierarchy, to make the source code less crufty. I can fix this by naming the union with a type name and member name, but I don't want to do that.

This is VS2012. Surprisingly, the compiler won't take it, but Intellisense does take it!

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
}

gives these messages

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

Ideally, I want to do this with anonymous/unnamed structs (which does work in some compilers, even though I realize it is not standard 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;
}

If I understand your question correctly, this should work:

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;
    };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM