有没有一种简单的方法将枚举类转换为字符串(c ++)?

时间:2015-01-14 09:25:56

标签: c++ enums

虽然有轻松convert an enum to a string的解决方案,但我希望使用enum class带来额外的安全优势。有没有一种简单的方法可以将enum class转换为字符串?

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

2 个答案:

答案 0 :(得分: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)];

如果那太冗长,那就由你来决定。

答案 1 :(得分: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'.
*/
相关问题