2

I have the following code (it's actually longer, i'm just putting up the part that throws an error)

//Header class
enum class Color{
    Rouge,  Bleu, Vert

};  

class Bike{
     Color _color;
     Bike (Color color): _color(color){
}

void print() const;
}

//Cpp file (assume all inclusions are done properly)
void Bike::print() const{
 std::cout<<_color;
}
//Main
main(){
    Color couleur (Color::Rouge);
    Bike obj(couleur);
    obj.print()


} 

So everything else works perfectly until i print the color (std::cout<<_color;). I'm i using enum in the wrong way? why can't i print that color?

error code

[Error] initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = Color]'
Apex Predator
  • 171
  • 1
  • 3
  • 13

1 Answers1

6

Apart from making your constructor and print function public, you should also know that enum class is not implicitly convertible to int. So you could either manually convert it to int in the print function:

std::cout << static_cast<int>(_color);

or overload the output operator for the Color:

std::ostream& operator<<(std::ostream& o, Color c)
{
    std::cout << static_cast<int>(c);
    return o;
}

This way, you could do some better output for your color - perhaps output a string representation of your enum values.

Here's a live example on cpp.sh

Rostislav
  • 3,857
  • 18
  • 30
  • 1
    Thank you, so if i want to output the actual string, i will have to do a bunch of `if-then else` statement? seems very inefficient – Apex Predator Oct 10 '15 at 15:00
  • 1
    @ApexPredator I'd search around if I were you for how to do this without kind of duplicating stuff. The simplest solution though is to use an array of names in the output operator: `static std::array enumNames = {"Red", "Blue", "Green"}; std::cout << enumNames[static_cast(c)];` – Rostislav Oct 10 '15 at 15:02