简体   繁体   English

使用typedef的struct中的C枚举定义

[英]C enum definition in struct with typedef

I found some problem with definition of enum inside a struct, I want to have something like: 我发现结构体中的enum定义存在一些问题,我想拥有以下内容:

typedef struct
{
    typedef enum { E1, E2, E3 } E;
    E e;
} S;

in VS2012 I have errors: 在VS2012我有错误:

error C2071: 'E' : illegal storage class
error C2061: syntax error : identifier 'E'
error C2059: syntax error : '}'

I found an explanation of C2071 but it is not the same case: http://msdn.microsoft.com/en-us/library/deb3kh5w.aspx 我找到了C2071的解释,但情况不一样: http : //msdn.microsoft.com/zh-cn/library/deb3kh5w.aspx

gcc-4.9 says: gcc-4.9说:

error: expected specifier-qualifier-list before ‘typedef’

the interesting thing is that the code: 有趣的是,代码:

typedef enum { E1, E2, E3 } E;
E e;

works fine in global scope and in function's body. 在全局范围和功能主体中都可以正常工作。

I've also tried to do it without typedef, but unfortunately there are still lot's of errors: 我也尝试过在没有typedef的情况下进行操作,但是不幸的是仍然存在很多错误:

error C2011: 'E' : 'enum' type redefinition
see declaration of 'E'
error C2208: 'E' : no members defined using this type

I found similar reason: http://msdn.microsoft.com/en-us/library/ms927163.aspx but I do define members of the type. 我发现了类似的原因: http : //msdn.microsoft.com/zh-cn/library/ms927163.aspx,但是我确实定义了该类型的成员。

You should declare your enum member like so: 您应该这样声明您的enum成员:

typedef struct
{
    enum { E1, E2, E3 } e;
} S;

then you can do: 那么您可以执行以下操作:

int main(void)
{
    S s;
    s.e = E1;

    /*  And so on  */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM