Union tested for current member in use

时光怂恿深爱的人放手 提交于 2020-01-11 02:07:29

问题


Do unions have a control structure to test which member is currently in use (or if it has any at all)? I'm asking this because undefined behavior is never a good thing to have in your program.


回答1:


No, no such mechanism exists off-the-shelf. You'll have to take care of that yourself. The usual approach is wrapping the union in a struct:

struct MyUnion
{
   int whichMember;
   union {
      //whatever
   } actualUnion;
};

So you have MyUnion x; and x.whichMember tells you which field of x.actualUnion is in use (you have to implement the functionality though).



来源:https://stackoverflow.com/questions/11035534/union-tested-for-current-member-in-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!