1

虽然有一些解决方案可以轻松地将枚举转换为字符串,但我希望使用enum class. 有没有一种简单的方法可以将 a 转换enum class为字符串?

(给出的解决方案不起作用,因为枚举类不能索引数组)。

4

2 回答 2

2

您不能隐式转换为基础类型,但可以显式转换。

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)];

是否过于冗长取决于您。

于 2015-01-14T09:33:44.657 回答
1

你在使用 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'.
*/
于 2015-01-14T09:34:45.143 回答