c ++如何在不同的枚举名称中使用相同的枚举成员名称而不会出现错误:redefinition; 以前的定义是'枚举'

use*_*898 28 c++ enums

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

enum GameObjectType
{
     NINJA_PLAYER

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


};
Run Code Online (Sandbox Code Playgroud)

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

m_pNinjaPlayer = (NinjaPlayer*)GameFactory::Instance().getGameObj(GameObjectType::NINJA_PLAYER);
    ComponentMadiator::Instance().Register(GameObjectTypeLocation::NINJA_PLAYER,m_pNinjaPlayer);
Run Code Online (Sandbox Code Playgroud)

我收到编译错误:

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'
Run Code Online (Sandbox Code Playgroud)

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

jua*_*nza 41

问题是旧式枚举是无范围的.您可以通过使用作用域枚举来避免此问题(假设您的编译器具有相关的C++ 11支持):

enum class GameObjectType { NINJA_PLAYER };

enum class GameObjectTypeLocation { NONE, MASSAGE_ALL, NINJA_PLAYER };
Run Code Online (Sandbox Code Playgroud)

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

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

namespace bar
{
  enum GameObjectTypeLocation { NONE, MASSAGE_ALL, NINJA_PLAYER };
} // namespace bar
Run Code Online (Sandbox Code Playgroud)

然后你的枚举值将是foo::NINJA_PLAYER,bar::NINJA_PLAYER等等.


Sam*_*uel 7

如果你有可能使用C++ 11,我建议使用枚举类功能来避免冲突:

enum class GameObjectType
{
     NINJA_PLAYER

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


};
Run Code Online (Sandbox Code Playgroud)

编辑:如果您没有此功能,则需要为每个枚举使用两个不同的命名空间.