0

I want to print u that has km as unit

enum class Unit { km, m, cm };

int main()
{
Unit u = Unit::km; 
std::cout<<u; 
return 0; 
}

Why do i get an error?

error:

error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘Unit’)
anatolyg
  • 26,506
  • 9
  • 60
  • 134
Tim
  • 415
  • 2
  • 10
  • 3
    **Always** include the verbatim error message(s) when you have questions about errors you receive when compiling code. It should be [included in your question](https://stackoverflow.com/posts/65342305/edit) – WhozCraig Dec 17 '20 at 14:09
  • When I run it I get `error: ‘cout’ was not declared in this scope` so I assume it's that? – Dock Dec 17 '20 at 14:11

1 Answers1

2

Your Unit enum is a scoped enumeration, enum class, these types of enums don't allow implicit casting. You'll have to expliticly cast if you want it to work with cout:

std::cout << static_cast<int>(u);
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122