gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:47:12 26 4
gpt4 key购买 nike

我有一个配置文件,我包含在我的所有文件中我有不同的枚举,但每个枚举内部都有相同的元素名称例如: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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com