简短回答:除了在联合体外部的结构体中添加枚举变量之外,没有其他方法。
enum TestUnionPart
{
TUP_STRUCT,
TUP_TOTAL
};
struct TestUnionStruct
{
enum TestUnionPart Part;
union
{
struct
{
unsigned int Num;
unsigned char Name[5];
} TestStruct;
unsigned char Total[7];
} TestUnion;
};
现在您需要控制联合的创建,以确保枚举正确设置,例如使用类似以下函数的函数:
void init_with_struct(struct TestUnionStruct* tus, struct TestStruct const * ts)
{
tus->Part = TUP_STRUCT;
memcpy(&tus->TestUnion.TestStruct, ts, sizeof(*ts));
}
现在,对于正确的值进行分发只需要一个开关:
void print(struct TestUnionStruct const * tus)
{
switch (tus->Part)
{
case TUP_STRUCT:
printf("Num = %u, Name = %s\n",
tus->TestUnion.TestStruct.Num,
tus->TestUnion.TestStruct.Name);
break;
case TUP_TOTAL:
printf("Total = %s\n", tus->TestUnion.Total);
break;
default:
assert(0);
}
}
作为一则旁注,我想提到这些结构最好在ML语言家族中处理。
type test_struct = { num: int; name: string }
type test_union = Struct of test_struct | Total of string
char
之后,而不是之前。严格来说,实现可以在它之前放置填充位,但是如果你从char [5]
更改为char[6]
,它还必须在它之前放置相同数量的填充位,这将非常荒谬。 C要求具有共同初始元素序列的结构是兼容的。 - R.. GitHub STOP HELPING ICE