c++如何在不同的枚举名称中具有相同的枚举成员名称而不会出现错误:redefinition; previous definition was 'enumerator'

标签 c++ enums

我有一个配置文件,我包含在我的所有文件中 我有不同的枚举,但每个枚举内部都有相同的元素名称 例如:config.h

enum GameObjectType
{
     NINJA_PLAYER

};
enum GameObjectTypeLocation
{
    NONE,
    MASSAGE_ALL,  //this is for ComponentMadiator
    NINJA_PLAYER


};

但是当我尝试使用正确的枚举名称调用枚举来编译项目时

m_pNinjaPlayer = (NinjaPlayer*)GameFactory::Instance().getGameObj(GameObjectType::NINJA_PLAYER);
    ComponentMadiator::Instance().Register(GameObjectTypeLocation::NINJA_PLAYER,m_pNinjaPlayer);

我收到编译错误:

error C2365: 'NINJA_PLAYER' : redefinition; previous definition was 'enumerator' (..\Classes\GameFactory.cpp)
2>          d:\dev\cpp\2d\cocos2d-x-3.0\cocos2d-x-3.0\projects\lettersfun\classes\config.h(22) : see declaration of 'NINJA_PLAYER'

如何在 config.h 中保留几个名称不同但元素名称相同的枚举?

最佳答案

问题在于旧式枚举没有作用域。您可以通过使用范围枚举来避免此问题(前提是您的编译器具有相关的 C++11 支持):

enum class GameObjectType { NINJA_PLAYER };

enum class GameObjectTypeLocation { NONE, MASSAGE_ALL, NINJA_PLAYER };

或者,您可以将旧式枚举放在命名空间中:

namespace foo
{
  enum GameObjectType { NINJA_PLAYER };
} // namespace foo

namespace bar
{
  enum GameObjectTypeLocation { NONE, MASSAGE_ALL, NINJA_PLAYER };
} // namespace bar

那么您的枚举值将是 foo::NINJA_PLAYERbar::NINJA_PLAYER 等。

关于c++如何在不同的枚举名称中具有相同的枚举成员名称而不会出现错误:redefinition; previous definition was 'enumerator' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288934/

相关文章:

c++ - 角色上的跳跃功能

java - 如何使用 JPA 和 Hibernate 使用映射为 ORDINAL 的枚举参数进行查询

enums - Rust 宏从另一个枚举生成枚举

c++ - 在 Windows/Linux 中检查对文件的写入权限

C++ 散列 : Open addressing and Chaining

C++ 单向链表 - 双端队列 - InsertFront()

c++ - 比较有符号比无符号整数更快

c# - 有没有办法为枚举类型实现一元运算符?

c++ - std::map 枚举的默认值

c - 带(有符号)枚举值的按位运算