在结构内部枚举

时间:2016-02-22 06:02:10

标签: c++ enums structure

我正在尝试这段代码:

#include <stdio.h>

namespace
{
    typedef enum
    {
        orange,
        banana,
        apple
    }fruit;
}

typedef struct Information
{
    int number;
    namespace::fruit choice;
}Information;

void input_structure()
{
    Information info;

    info.number = 5;
    info.choice = orange;

    printf("Number = %d\n", info.number);
    printf("Choice: %d\n", info.choice);
}

int main()
{
    input_structure();

    return 0;
}

编译因以下错误而失败:

error C2039: 'choice' : is not a member of 'Information'

虽然我明白这个错误是什么,但我无法纠正它。 有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

在引用命名空间内的实体时,您不应该使用namespace关键字对其进行限定。您所需要的只是命名空间的名称,例如std::vector。由于您有一个未命名的(匿名)命名空间,因此只需按原样引用它。删除它使程序编译并运行:live demo。如果您必须引用全局命名空间中的某些内容,则可以使用::,例如::f();

顺便说一句,你不需要typedef,因为这是C ++;你可以写

struct Information
{
    int number;
    fruit choice;
};

答案 1 :(得分:0)

我得到的错误是

g++ -std=c++11 -g -Wall -Wextra -Wwrite-strings    -c -o 35546727.o 35546727.cpp
35546727.cpp:16:5: error: expected unqualified-id before ‘namespace’
     namespace::fruit choice;
     ^
35546727.cpp: In function ‘void input_structure()’:
35546727.cpp:24:10: error: ‘Information’ has no member named ‘choice’
     info.choice = orange;
          ^
35546727.cpp:27:33: error: ‘Information’ has no member named ‘choice’
     printf("Choice: %d\n", info.choice);
                                 ^

第一个错误是要处理的错误。匿名命名空间没有名称;它不被称为&#39; namespace&#39;。所以你应该写:

    fruit choice;

而不是

    namespace::fruit choice;

Information

的定义中

请注意typedef struct foo {} foo是写作的C方式;在C ++中我们只写

struct Information
{
    int number;
    fruit choice;
};