7

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

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

I have a Player defined like so:

using namespace std;

enum PlayerType { FORWARD, DEFENSEMAN, GOALIE };

class Player {
  public:
    Player();
    void setType(PlayerType);
  private:
    PlayerType type;
};

This is how I try to call the method in main ...

#include "Player.h"
#include "Manager.h"

int main() {

  Manager manager;
  Player player;
  PlayerType t = PlayerType::FORWARD;
  manager.createPlayer(player, t);

  return 0;
}

... but it fails to compile with this error:

Main.cc: In function ‘int main()’:
Main.cc:12:18: error: ‘PlayerType’ is not a class or namespace

Any ideas? Note: I cannot change the signature of the createPlayer method.

4 Answers4

11

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.

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
7

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;
Shoe
  • 74,840
  • 36
  • 166
  • 272
1

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

HEGG
  • 11
  • 1
0

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.

AMIC MING
  • 6,306
  • 6
  • 46
  • 62
Pete
  • 1