c++ - Why does named union inside struct overwriting other struct members? -
struct teststruct { int a; int b; union { char c[2]; int d; }; }; teststruct instance;
if do
instance.a = 100; instance.b = 200; instance.d = 300;
everything's fine.
but, if give union name:
struct teststruct { int a; int b; union zzz // note here!! { char c[2]; int d; }; }; teststruct instance;
and same things again:
instance.a = 100; instance.b = 200; instance.zzz::d = 300;
then
instance.zzz::d = 300;
is overwriting instance.a
300
, why?!
additionally, can not see union members in debugger watch list if has name.
i using visual studio 2008.
when name union there no longer data member in class corresponding d
instance.zzz::d = 300;
doesn't mean anything. (with vs2012 "error c2039: 'zzz' : not member of 'teststruct'")
to have member of union type you'll have give name.
struct teststruct { int a; int b; union zzz // note here!! { char c[2]; int d; } z; }; instance.a = 100; instance.b = 200; instance.z.d = 300;
c++ has special rule 'anonymous unions', unnamed union type of form union {
member-specification
};
creates unnamed object. names of union's members injected enclosing scope , access unnamed object's members.
that's you're getting when don't name union type inside class. give type name union no longer matches special rule , there's no longer unnamed union member in class; have add union data member normally, naming member variable.
Comments
Post a Comment