结构中的枚举-C与C ++ [英] Enumerations within a struct - C vs C++

查看:73
本文介绍了结构中的枚举-C与C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

#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);
}

使用 gcc :

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

通过 g ++ 获得的输出:

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


推荐答案

MODE1 foo 的范围内,因此您需要

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;
};

这篇关于结构中的枚举-C与C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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