【问题标题】:Enums within a class, with explicit scoping, pre-C++11?类中的枚举,具有显式作用域,C++11 之前?
【发布时间】:2013-03-05 06:01:05
【问题描述】:

我使用 VS2010,它没有 C++11 的强类型枚举。我可以没有强类型,但无论如何,我希望将枚举排除在我的类的命名空间之外。

class Example{
    enum Color{
        red,
        green,
        blue
    };

    int Rainbows{
        Color x = red;           // this should be impossible
        Color y = Color::green;  // this is the only way at the enumerations
    }
};

我的问题是,在 C++11 之前,最好的方法是什么?

【问题讨论】:

    标签: c++ visual-studio-2010 enums namespaces


    【解决方案1】:
    namespace ExampleColor {
       enum Color {
         red,
         green,
         blue
       };
    }
    
    class Example {
       int Rainbows{ExampleColor::Color x = ExampleColor::red};
    };
    

    【讨论】:

    • using namespace ExampleColor; Color x = red; // this should be impossible
    • @Spook 是的,但它是 C++11 之前使用“范围”枚举的常见变体。
    • 也许吧。但是 OP 希望分配 x = red; 不可能,但在你的例子中它仍然是。此外,Color 被定义为子类 - 您不能将命名空间插入到类中,对吗?
    • 虽然,我不得不同意,它比带有类的版本更容易实现:) 我猜,这一切都取决于 OP 的需求。
    • @Spook - 嗯,技术上是的!但如果我使用using,那就是我的错。我的目标只是防止枚举在我的 IDE 中的类的命名空间中列出,这样就可以了。
    【解决方案2】:

    我会尝试以下方法:

    class Color
    {
    private:
        int value;
    
        Color(int newValue)
        {
            value = newValue;
        }
    
    public:
        static Color red;
        static Color green;
        static Color blue;
    };
    
    Color Color::red = Color(1);
    Color Color::green = Color(2);
    Color Color::blue = Color(4);
    
    int main(int argc, char * argv[])
    {
        Color color = Color::red;
    }
    

    【讨论】:

    • 这不是很多代码,只是为了确定范围吗?每个额外的枚举值都需要添加到两个不同的位置。
    • 这取决于您的需求。如果您需要安全范围,您将选择我的选项。如果您只需要 Name::Value 符号,您可以使用 ForEveR 的解决方案。
    • 实际上,== 和 = 运算符似乎不是必需的,默认实现应该可以正常工作(删除它们)。
    • 啊,我明白了!谢谢,虽然我是一个懒惰的程序员,所以编码越少越好(我使用的实际枚举将枚举分配给键盘上的每个键,所以大约有 120 个条目)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    相关资源
    最近更新 更多