Implicit type conversion (coercion) to and from type int is not possible with scoped enumerations. Your source code will compile if you explicitly cast the variable to type int with the static_cast operator.
1 2 3 4 5 6 7 8 9
#include <iostream>
usingnamespace std;
int main()
{
enumclass StatusA : int {STARTED, FINISHED};
StatusA ProgramStatusA = StatusA::STARTED;
cout<<static_cast<int>(ProgramStatusA)<<endl;
}
As you know the code is working perfect now. I still don't get why I have to cast to int when I already specified that the enum identifier type is int during the enum declaration. Regardless of what type the identifier is, why does cout have issues with outputting it? Should cout not just output whatever ProgramStatusA is regardless of it's type? Why does cout "care"?
P.s. I am learning from the Deitel How to Program 9th Edition (updated for C++11) and it only gives a brief mention of scoped enums with no mention of having to perform explicit type conversion (by the way, I thought that specifying the enum type as int during the declaration was explicit!).
enum class do two things.
1. It forces you do access the enumerators by prefixing the enum name. EnumName::enumerator
2. It prevents implicit conversions to the underlying type.
It is a bit sad that we can't get one without the other.
Specifying the underlying type can be done for all enums, not just enum class.