I have the following enum class:
enum class EnumClass : int
{
A = 0, B
};
Now I want to subscript with that enum type to an array:
MyObject arr[2];
.
.
.
MyObject a = arr[EnumClass::A]
MyObject b = arr[EnumClass::B]
Unfortunately I get the following error message:
array subscript is not an integer
As enum classes are strongly typed I would expect this to work.
If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on.
So yes, if you do not specify a start value, it will default to 0.
The size of an enum is compiler-specific and should default to the smallest integral type which is large enough to fit all of the values, but not larger than int. In this case, it seems the sizeof enum is fixed at 16-bit.
By default, the starting code value of the first element of enum is 0 (as in the case of array) . But it can be changed explicitly. For example: enum enumerated-type-name{value1=1, value2, value3}; And, The consecutive values of the enum will have the next set of code value(s).
As enum classes are strongly typed I would expect this to work
On the contrary, that's exactly why it won't work. Scoped enumerations will not implicitly convert to the underlying type. Use static_cast
instead.
MyObject a = arr[static_cast<int>(EnumClass::A)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With