虽然有一些解决方案可以轻松地将枚举转换为字符串,但我希望使用enum class
. 有没有一种简单的方法可以将 a 转换enum class
为字符串?
(给出的解决方案不起作用,因为枚举类不能索引数组)。
虽然有一些解决方案可以轻松地将枚举转换为字符串,但我希望使用enum class
. 有没有一种简单的方法可以将 a 转换enum class
为字符串?
(给出的解决方案不起作用,因为枚举类不能索引数组)。
您不能隐式转换为基础类型,但可以显式转换。
enum class colours : int { red, green, blue };
const char *colour_names[] = { "red", "green", "blue" };
colours mycolour = colours::red;
cout << "the colour is" << colour_names[static_cast<int>(mycolour)];
是否过于冗长取决于您。
你在使用 VS C++。下面是 MSDN 的代码示例
using namespace System;
public ref class EnumSample
{
public:
enum class Colors
{
Red = 1,
Blue = 2
};
static void main()
{
Enum ^ myColors = Colors::Red;
Console::WriteLine( "The value of this instance is '{0}'", myColors );
}
};
int main()
{
EnumSample::main();
}
/*
Output.
The value of this instance is 'Red'.
*/