-2

I had this question on a test.

I know that I can do something like:

enum class Color { red, green = 1, blue };
Color c = Color::blue;

if( c == Color::blue )
cout << "blue\n";

But when I replace cout << "blue\n"; with cout << Color::green, it doesn't even compile. Why doesn't it compile?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
vister
  • 31
  • 5
  • 3
    You have a lower case c in the cout call. – Bathsheba Apr 16 '18 at 17:53
  • @Bathsheba Even with your comment I had to look thrice to see it. Well spotted. My respect. – Yunnosch Apr 16 '18 at 17:54
  • When compiling, what actually is the error you get? And what are the warnings your get with strict level? – Yunnosch Apr 16 '18 at 17:56
  • 2
    What did your compiler say? Ususally,when the code _'does not even compile'_, the compiler says something about the reason... :) – CiaPan Apr 16 '18 at 17:58
  • Uppercase doesn't work either. – vister Apr 16 '18 at 17:59
  • I realize that the error message you get from your compilers is probably a nearly intractable wall of text. In situations like that it helps to include the initial few lines from that "wall", otherwise you run a high chance of the question being closed for not including an explanation of what is broken. – Sergey Kalinichenko Apr 16 '18 at 18:04
  • 1
    Voting to reopen, it is not a typo and, at least in this case, an error message is not needed to be answerable. – NathanOliver Apr 16 '18 at 18:05
  • Remove `class` keyword and it will compile. Or `static_cast(Color::blue)` – Killzone Kid Apr 16 '18 at 18:30

1 Answers1

5

This error happens because C++ does not have a pre-defined way of printing an enum. You need to define an operator << for printing objects of Color enum type according to your needs.

For example, if you would like to print the numeric value, cast the color to int inside your operator:

ostream& operator<<(ostream& ostr, const Color& c) {
    ostr << (int)c;
    return ostr;
}

Demo.

If you would like to print enum value as text, see this Q&A for a sample implementation.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523