【问题标题】:typedef an existing enum type, possible?typedef 一个现有的枚举类型,可能吗?
【发布时间】:2011-04-28 14:25:25
【问题描述】:

鉴于以下情况:

namespace otherns
{
    enum MyEnum_e { MyEnum_YES, MyEnum_NO };
}

namespace myns
{
    typedef otherns::MyEnum_e MyEnum_e;
}

为什么以下无效?

int e = myns::MyEnum_YES;

我得到一个编译器错误说明:

'MyEnum_YES' is not a member of 'myns'

【问题讨论】:

    标签: c++ enums typedef


    【解决方案1】:

    因为枚举值位于命名空间 otherns 中,而不是 MyEnum_e 的子代:要引用 MyEnum_YES,请键入 otherns::MyEnum_YES

    你可以试试这个:

    namespace otherns
    {
        namespace MyEnum_e_space {
        enum MyEnum_e { MyEnum_YES, MyEnum_NO };
        }
        using namespace MyEnum_e_space;
    }
    
    namespace myns
    {
        using namespace otherns::MyEnum_e_space;
    }
    

    虽然不鼓励使用using..

    【讨论】:

    • 不气馁,慎用;经验法则是:不在头文件中(因为您不想在头文件的任何奇怪的未来客户端上造成名称空间污染甚至符号解析冲突)。随意在您自己的编译单元中使用using
    猜你喜欢
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    相关资源
    最近更新 更多