枚举在结构;新手在C [英] enum in a struct; newbie in a c

查看:201
本文介绍了枚举在结构;新手在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆