假设我们有一个联合:
typedef union someunion {
int a;
double b;
} myunion;
字符串
在我设置了,例如,a=123,我的方法是将这个联合添加到某个结构中,当它是int时,将uniontype设置为1,当它是double时,将uniontype设置为2。
typedef struct somestruct {
int uniontype
myunion numbers;
} mystruct;
型
有没有更好的解决办法?
7条答案
按热度按时间eoigrqb61#
有没有更好的解决办法?
不,您展示的解决方案是最好的(也是唯一的)解决方案。
union
是非常简单的--它们不“跟踪”您将什么分配给了什么。它们所做的一切就是让你为它们的所有成员重用相同的内存范围。除此之外,它们不提供任何其他功能,因此将它们包含在struct
中并使用“type”字段进行跟踪正是正确的做法。njthzxwz2#
C不会自动跟踪联合中当前正在使用的字段。(事实上,我相信从“错误”字段阅读会导致实现定义的行为。)因此,由您的代码来跟踪当前使用/填写的是哪个字段。
您保持一个单独的'uniontype'变量的方法是一种非常常见的方法,应该可以很好地工作。
vcudknz33#
无法直接查询当前存储在
union
中的类型。知道
union
中存储的类型的唯一方法是使用显式标志(如mystruct
示例中所示),或者确保当联合体具有已知的活动元素时,控制只流向代码的某些部分。ycggw6v24#
根据应用程序的不同,如果它是一个短期对象,您可以在控制流中对类型进行编码,即。对于两种情况具有单独的块/功能
字符串
apeeds0o5#
你可以使用一些丑陋的技巧来做到这一点(只要你的联合中的数据类型有不同的大小,这就是目前的情况):
字符串
但我建议你永远不要这么做。
x7rlezfr6#
也许我的变种在起作用
字符串
00jrzges7#
没有直接的方法来检查存储在联合体中的数据类型。因此,您负责跟踪联合中的类型。
为了更好的可读性,使用Enum而不是int可能是一个好主意。
字符串