c ++如何在不同的枚举名称中使用相同的枚举成员名称而不会出错:重新定义;以前的定义是“枚举器" [英] c++ how to have same enum members name in different enum names without getting err:redefinition; previous definition was 'enumerator'

查看:46
本文介绍了c ++如何在不同的枚举名称中使用相同的枚举成员名称而不会出错:重新定义;以前的定义是“枚举器"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have config file that I include in all my files there I have different enums but inside each enum there are same element names for example: config.h

enum GameObjectType
{
     NINJA_PLAYER

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


};

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

But when I try to compile the project with calling the enums with the proper enum name

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' (..ClassesGameFactory.cpp)
2>          d:devcpp2dcocos2d-x-3.0cocos2d-x-3.0projectslettersfunclassesconfig.h(22) : see declaration of 'NINJA_PLAYER'

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

How can I keep in the config.h several enums with different names BUT with same elements names ?

推荐答案

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

The problem is that old-style enumerations are unscoped. You can avoid this problem (provided your compiler has the relevant C++11 support) by using scoped enumerations:

enum class GameObjectType { NINJA_PLAYER };

enum class GameObjectTypeLocation { NONE, MASSAGE_ALL, NINJA_PLAYER };

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

Alternatively, you can put your old-school enumerations in namespaces:

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

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

那么你的枚举值将是 foo::NINJA_PLAYERbar::NINJA_PLAYER

Then your enum values will be foo::NINJA_PLAYER, bar::NINJA_PLAYER etc.

这篇关于c ++如何在不同的枚举名称中使用相同的枚举成员名称而不会出错:重新定义;以前的定义是“枚举器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆