如何避免 C++ 中两个同名枚举值的名称冲突?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10869790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:33:40  来源:igfitidea点击:

How to avoid name conflicts for two enum values with the same name in C++?

c++enums

提问by bytecode77

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

C++ 中的枚举有一个主要问题:在两个不同的枚举中不能有一个名称,如下所示:

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

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

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

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

回答by iammilind

In C++03 you can enclose enuminside a struct:

在 C++03 中,您可以包含enum在一个struct:

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

In C++11 make it an enum class:

在 C++11 中使其成为enum class

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

In C++03 namespacealso can be wrapped, but personally I find wrapping struct/classbetter because namespaceis more broader. e.g.

在 C++03 中namespace也可以包装,但我个人觉得包装struct/class更好,因为namespace它更广泛。例如

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

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

回答by juanchopanza

One option is to put each enum in a different namespace:

一种选择是将每个枚举放在不同的命名空间中:

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

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

A better option, if available with your compiler, is to use C++11 enum classes:

如果您的编译器可用,则更好的选择是使用 C++11枚举类

enum class Browser { ... }
enum class OS { ... }

See herefor a discussion on enum classes.

有关枚举类的讨论,请参见此处

回答by Not_a_Golfer

Either wrap them in namespaces or in classes:

将它们包装在命名空间或类中:

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

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

回答by DML

You can use enum class(scoped enums) which is supported in C++11 on up. It is strongly typed and indicates that each enumtype is different.

您可以使用C++11 支持的enum class( scoped enums)。它是强类型的,表示每种enum类型都不同。

Browser::None != OS::None   

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

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

回答by user633658

How about using scoped vs. unscoped enumeration? c++11 now offers scoped enumeration. An example would be:

如何使用作用域和非作用域枚举?c++11 现在提供作用域枚举。一个例子是:

enum class Browser : <type> {

};

enum class OS : <type> {

};

Access the enumerated types via an object of the Browser or an object of OS.

通过浏览器对象或操作系统对象访问枚举类型。