Why am I getting this 'enum' is not a class or a namespace error?

前端 未结 4 1976
粉色の甜心
粉色の甜心 2020-12-10 18:10

I need call a method with this signature in my Manager class:

void createPlayer(Player& player, PlayerType& playerType);

I have a P

相关标签:
4条回答
  • 2020-12-10 18:28

    Your error seems to be in this line: PlayerType t = PlayerType::FORWARD;

    As far as I know, the scope resolution operator (::) is not valid on regular C++98 enums unless your compiler supports them through non-standard extensions (like Visual Studio). Therefore you can't use it to reference an specific value from the enumerator.

    Also, C++98 enums have the problem of polluting the namespace in which they are defined which can lead to name clash. Luckily C++11 solved this introducing the enum class. For more information check Stroustrup's FAQ: http://www.stroustrup.com/C++11FAQ.html#enum

    0 讨论(0)
  • 2020-12-10 18:38

    enum doesn´t create a namespace.

    Therefor PlayerType t = PlayerType::FORWARD; should be changed to:

    PlayerType t = FORWARD;
    

    Notice that c++11 introduce enum classes, which have a namespace. Beside this MSVC has an extension which treats (regular) enums like they have namespace. So your code should actually work with MSVC.

    0 讨论(0)
  • 2020-12-10 18:54

    Unfortunately enum by default doesn't create an enum namespace. So when declaring:

    enum PlayerType { FORWARD, DEFENSEMAN, GOALIE };
    

    you'll have to use it like this:

    auto x = FORWARD;
    

    Thankfully, though, C++11 introduced enum class or enum struct to solve this issue:

    enum class PlayerType { FORWARD, DEFENSEMAN, GOALIE };
    

    You'll then be able to access it like you did:

    auto x = PlayerType::FORWARD;
    
    0 讨论(0)
  • 2020-12-10 18:55

    add a static function say getForward:

    class Player {
      public:
        Player();
        void setType(PlayerType);
        static PlayerType getForward {
            return FORWARD;
        }
      private:
        PlayerType type;
    };
    

    Then use it in main:

    manager.createPlayer(player, Player::getForward());
    

    This should work.

    0 讨论(0)
提交回复
热议问题