我有以下枚举类:
enum class EnumClass : int { A = 0,B };
现在我想用枚举类型下标到数组:
MyObject arr[2]; . . . MyObject a = arr[EnumClass::A] MyObject b = arr[EnumClass::B]
不幸的是我收到以下错误消息:
array subscript is not an integer
由于枚举类是强类型的,我希望这可以工作.
解决方法
As enum classes are strongly typed I would expect this to work
相反,这正是它无法运作的原因. Scoped枚举不会隐式转换为基础类型.请改用static_cast.
MyObject a = arr[static_cast<int>(EnumClass::A)];