The C++11 standard introduces the scoped enumerators.
Unlike the old enumerators, the scoped enumerators do not leak their names into the surrounding scope.
Scoped enums have the following signature: enum class Enumerator_Name {value1, value2 etc} signature.
To define a scoped enum, we write:
enum class MyEnum { myfirstvalue, mysecondvalue, mythirdvalue };
To declare a variable of type enum class (scoped enum) we write:
enum class MyEnum { myfirstvalue, /*from ww w . j av a 2s. c o m*/ mysecondvalue, mythirdvalue }; int main() { MyEnum myenum = MyEnum::myfirstvalue; }
To access an enumerator value, we prepend the enumerator with the enum name and a scope resolution operator :: such as MyEnum::myfirstvalue
, *MyEnum:: mysecondvalue*, etc.
With these enums, the enumerator names are defined only within the enum internal scope and implicitly convert to underlying types.
We can specify the underlying type for scoped enum:
enum class MyCharEnum : char { myfirstvalue, mysecondvalue, mythirdvalue };
We can also change the initial underlying values of enumerators by specifying the value:
enum class MyEnum { myfirstvalue = 15, mysecondvalue, mythirdvalue = 30 };