2014-06-12 37 views
1

當我使用匿名union時,如何正確訪問成員數據和枚舉符號?匿名工會的全部觀點都留下了一層層次結構,以使源代碼更簡潔。我可以通過將類型名稱和成員名稱命名爲union來解決此問題,但我不想那樣做。如何使用匿名聯合使用枚舉?

這是VS2012。令人驚訝的是,編譯器不會接受它,但Intellisense確實需要它!

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

[是相關](http://stackoverflow.com/questions/17637392/anonymous-union-can-only-have-non-static-data-members-gcc-c)? – Gluttton

+0

@Gluttton - 我不這麼認爲 –

+0

_§9.5/5 - 匿名工會的成員規範只能定義非靜態數據成員。 [注意:嵌套類型和函數不能在匿名聯合中聲明。 - 結束註釋] _是否相關? – Gluttton

回答

2

如果我正確理解你的問題,這應該工作:

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

這對我很有用。 –