一个结构里面枚举 - Visual C VS C ++ [英] enums inside a struct - C vs C++
本文介绍了一个结构里面枚举 - Visual C VS C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用结构内枚举和这个编译并正常工作与 GCC
。
但与 G ++
编译同一code会抛出错误。
#包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
结构美孚
{
枚举{模式1,模式2,模式3}模式;
枚举{TYPE1,TYPE2}类型;
};
空巴(结构* foo的酒吧)
{
酒吧,>模式=模式1;
}诠释的main()
{
结构美孚*富=(结构美孚*)malloc的(的sizeof(结构富));
酒吧(富);
的printf(模式=%d个\\ N,foo->模式);
}
有关GCC输出
-bash-4.1 $ GCC的foo.c
-bash-4.1 $ ./a.out
模式= 0
关于g ++输出
-bash-4.1 $ G ++的foo.c
foo.c的:在功能无效栏(富*):
foo.c的:11:错误:MODE1在此范围未声明
解决方案
MODE1
是富
的范围,所以你需要
酒吧,>模式= :: foo的MODE1;
请注意,如果您要访问的枚举类型没有范围,你就需要声明他们。例如:
的typedef枚举{模式1,模式2,模式3}方式;
的typedef枚举{TYPE1,TYPE2}类型;结构美孚
{
MODE模式;
TYPE类型;
};
I'm trying to use enums inside a struct and this compiles and works fine with gcc
.
But the same code when compiled with g++
throws error.
#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 for gcc
-bash-4.1$ gcc foo.c
-bash-4.1$ ./a.out
mode=0
Output for g++
-bash-4.1$ g++ foo.c
foo.c: In function ‘void bar(foo*)’:
foo.c:11: error: ‘MODE1’ was not declared in this scope
解决方案
MODE1
is in the scope of foo
, so you need
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;
};
这篇关于一个结构里面枚举 - Visual C VS C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文