结构中的枚举 - C 与 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23462307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:27:32  来源:igfitidea点击:

Enumerations within a struct - C vs C++

c++cgccstructenums

提问by arunmoezhi

I'm trying to use Enums within a struct, this compiles and works fine with gcc. But the same code when compiled with g++throws an error.

我正在尝试在结构中使用枚举,这可以编译并与gcc. 但是编译时相同的代码g++会引发错误。

#include<stdio.h>
#include<stdlib.h>
struct foo
{
    enum {MODE1, MODE2, MODE3} mode;
    enum {TYPE1, TYPE2} type;
};
void bar(struct foo* bar)
{
    bar->mode = MODE1;
}

int main()
{
    struct foo* foo = (struct foo*) malloc(sizeof(struct foo));
    bar(foo);
    printf("mode=%d\n",foo->mode);
}

Output obtained with gcc:

获得的输出gcc

 $ gcc foo.c
 $ ./a.out
 mode=0

Output obtained with g++:

获得的输出g++

 $ g++ foo.c
 foo.c: In function ‘void bar(foo*)':
 foo.c:11: error: ‘MODE1' was not declared in this scope

回答by juanchopanza

MODE1is in the scope of foo, so you need

MODE1在 的范围内foo,所以你需要

bar->mode = foo::MODE1;

Note that if you want to access the enum types without a scope, you would need to declare them so. For example:

请注意,如果您想在没有作用域的情况下访问枚举类型,则需要如此声明它们。例如:

typedef enum {MODE1, MODE2, MODE3} MODE;
typedef enum {TYPE1, TYPE2} TYPE;

struct foo
{
    MODE mode;
    TYPE type;
};