枚举在结构;新手在C [英] enum in a struct; newbie in a c
问题描述
我想了解一下使用的语法的枚举
在结构
(在<$ ç$ C> C 的)
I'm wondering about the syntax of using an enum
in a struct
(in C
)
我见过各种各样的例子,一个结构
+ 联盟
/ 枚举
组合用来创建一个复杂的类型,例如:
I've seen various examples where a struct
+ union
/enum
combination was used to create a complex type, for example:
struct MyStruct{
enum{
TYPE_1,
TYPE_2,
TYPE_3,
} type;
union{
int value_1;
int value_2;
int value_3;
} value;
};
// ...
struct MyStruct test_struct;
不管怎么说,从这个例子中,我如何保存/测试当前的类型为每枚举
字段?
如果我有一个指针 test_struct
,这似乎并没有工作;踢回一个未知成员错误:
If I have a pointer to test_struct
, this doesn't seem to work; kicking back an unknown member error:
struct MyStruct *test_pointer = &test_struct;
test_pointer->value = test_pointer->VALUE_1;
我只是好奇,我是否需要访问枚举
值作为全球价值观?
test_pointer->value = VALUE_1;
任何澄清会大大AP preciated。
Any clarifications would be greatly appreciated.
推荐答案
这样一个结构的预期使用情况会是这样的:
The intended usage of such a struct would be something like that:
switch (test_struct.type) {
case TYPE_1:
printf("%d", test_struct.value.value_1);
break;
case TYPE_2:
printf("%d", test_struct.value.value_2);
break;
case TYPE_3:
printf("%d", test_struct.value.value_3);
break;
}
需要注意的是资本 VALUE_1
, VALUE_2
和 VALUE_3
不正确,因为它们不是常数,但工会的成员,而
Note that capitalising VALUE_1
, VALUE_2
and VALUE_3
is incorrect because they are not constants but rather members of the union.
TYPE_1
, TYPE_2
和 TYPE_3
将是全球范围内四通八达,无论是相应的枚举
所在的结构。
TYPE_1
, TYPE_2
and TYPE_3
will be globally accessible, no matter that the corresponding enum
resides in the struct.
这篇关于枚举在结构;新手在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!