C ++枚举类整数不适用于数组下标 [英] c++ enum class integer not working for array subscript
本文介绍了C ++枚举类整数不适用于数组下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下枚举类:
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.
推荐答案
由于枚举类是强类型的,所以我希望它能起作用
As enum classes are strongly typed I would expect this to work
恰恰相反,这就是为什么它不起作用的原因.作用域枚举不会隐式转换为基础类型.改用 static_cast
.
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)];
这篇关于C ++枚举类整数不适用于数组下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文