c ++如何在不同的枚举名称中使用相同的枚举成员名称而不会出错:重新定义;以前的定义是“枚举器"

2023-08-26C/C++开发问题
4

本文介绍了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 ++如何在不同的枚举名称中使用相同的枚举成员名称而不会出错:重新定义;以前的定义是“枚举器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6