C ++中枚举的最佳做法

C ++中枚举的最佳做法

问题描述:

C ++中的枚举有一个主要问题:您不能在两个不同的枚举中使用一个名称,例如:

Enums in C++ have one major problem: You can't have one name in two different enums like this:

enum Browser
{
    None = 0,
    Chrome = 1,
    Firefox = 2
}

enum OS
{
    None = 0,
    XP = 1,
    Windows7 = 2
}


b $ b

那么在这个例子中处理这个问题的最好方法是什么?

So what is the best way to handle this issue in this example?

您可以在 struct 内包含枚举

struct Browser
{
  enum eBrowser
  {
    None = 0,
    Chrome = 1,
    Firefox = 2
  };
};

在C ++ 11中使用枚举类

In C++11 make it an enum class:

enum class Browser
{
    None = 0,
    Chrome = 1,
    Firefox = 2
};

在C ++ 03 命名空间包装,但我个人发现包装 struct / class 更好,因为命名空间更广泛。例如

In C++03 namespace also can be wrapped, but personally I find wrapping struct/class better because namespace is more broader. e.g.

// file1.h
namespace X
{
  enum E { OK };
}

// file2.h
namespace X
{
  enum D { OK };
}