0

I am writing a game in which there are 2 players, "BLACK" and "WHITE".

I have the following enum class:

enum class PlayerType
{
    BLACK, WHITE
};

I would like to write an ostream operator<< for this class. Here is my attempt:

std::ostream& operator<<(std::ostream& os, const PlayerType& pt)
{
    if(pt == PlayerType::BLACK)
        os << "Black";

    return os;
}

However I get the following compiler error:

operator<< must take exactly 1 argument

I think the problem is that I am nesting the enum class, and operator<< inside another class; class Player.

Is there anything I can do about this without removing the enum from within this class?

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

2 Answers2

2

Is there anything I can do about this without removing the enum from within this class?

If it makes sense, you can declare the operator as a friend of Player. This makes it a non-member. However, you need to ask yourself if friendship is really the relation you need between operator and class. If not, move the operator outside of the class definition.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

When declaring any of the binary operators as a non-static member they'll take one argument in addition to the implicit object pointed to by this. The object pointed to by this is always the left-hand argument of the binary operator and the declared argument is the right-hand argument. Operators with additional arguments are not legal.

Since the stream classes need to be on the left-hand of the << operator you can't define the stream operators as non-static members. Making them non-member function is the only real option. Using a friend function to define the output operator still effectively declares a non-member function.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380