struct in union initialize

2019-09-21 17:23发布

问题:

Currently, I have a struct in a union. For example,

Struct foo{
    Union u{
         Struct s1{
             int i1;
         } ss1;
         Struct s2{
             int i2;
         } ss2;
    } wrap;
};

So when I want to initialize the union, I tried to do like this.

foo f = {};
f.u.ss1 = {
    .i1 = 0;
}

But the error shows no match for operator = (operand types and braced-enclosed initializer list).

So what is the right way to do the initialize? Thanks in advance.

回答1:

The initialisation should be:

foo f;
f.wrap.ss1 = {0 /*, comma seperated values, */};