Reputation: 7506
cout
unscoped enum directly works:
#include <iostream>
using namespace std;
enum color { red, green, blue };
int main()
{
cout << color::green;
return 0;
}
While with socoped enum can't:
#include <iostream>
using namespace std;
enum class color { red, green, blue };
int main()
{
cout << color::green;
return 0;
}
What's the difference?
Upvotes: 2
Views: 427
Reputation: 4244
Maybe char like optimal attribute help you.
#include <iostream>
using namespace std;
enum class Color { red='r', green='g', blue='b' };
int main()
{
cout << "Print opt attribute: " << static_cast<char>(Color::green);
return 0;
}
Test online :
https://onlinegdb.com/Syw-qgg97
Upvotes: 0
Reputation: 23681
The unscoped enum is automatically converted to some integral type. That's why it will only print out 1
, not green
.
The scoped enum is not implicitly convertable to an integer and there is not other operator<<
for std::cout
so it fails to compile.
Upvotes: 1
Reputation: 119099
This works because unscoped enums can be implicitly converted to integers, whereas scoped enums can't, and require an explicit conversion:
cout << static_cast<int>(color::green);
Upvotes: 5