Statically initialize anonymous union in C++

前端 未结 4 1897
有刺的猬
有刺的猬 2021-01-17 11:01

I am trying to statically initialize the following structure in Visual Studio 2010:

struct Data
{
   int x;
   union
   {
      const Data* data;
      struc         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-17 11:42

    Can you do it by defining overloaded constructors? Untested code ahead:

    struct Data 
    { 
        int x; 
        union 
        { 
            const Data* data; 
            struct {int a; int b; } z; 
        } y;
    
        Data()
        {
            x = 0;
            y.data = 0;
            y.z.a = 0;
            y.z.b = 0;
        }
    
        Data(int x_, Data* data_)
        {
            x = x_;
            y.data = data_;
        }
    
        Data(int x_, int a_, int b_)
        {
            x = x_;
            y.z.a = a_;
            y.z.b = b_;
        }
    }; 
    
    static Data d1; 
    static Data d(1, &d1); 
    static Data d2(1, 1, 2); 
    

提交回复
热议问题