c++ how to have same enum members name in different enum names without getting err:redefinition; previous definition was #39;enumerator#39;(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_PLAYER、bar::NINJA_PLAYER 等
Then your enum values will be foo::NINJA_PLAYER, bar::NINJA_PLAYER etc.
这篇关于c ++如何在不同的枚举名称中使用相同的枚举成员名称而不会出错:重新定义;以前的定义是“枚举器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c ++如何在不同的枚举名称中使用相同的枚举成员名称而不会出错:重新定义;以前的定义是“枚举器"
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
