Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

c++ how to have same enum members name in different enum names without getting err:redefinition; previous definition was 'enumerator'

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);

I am getting compilation error:

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'

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

question from:https://stackoverflow.com/questions/23288934/c-how-to-have-same-enum-members-name-in-different-enum-names-without-getting-e

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...