枚举到字符串 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6281461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:49:59  来源:igfitidea点击:

Enum to String C++

c++enums

提问by bobobobo

I commonly find I need to convert an enum to a string in c++

我通常发现我需要在 C++ 中将枚举转换为字符串

I always end up doing:

我总是最终做:

enum Enum{ Banana, Orange, Apple } ;

char * getTextForEnum( int enumVal )
{
  switch( enumVal )
  {
  case Enum::Banana:
    return "bananas & monkeys";
  case Enum::Orange:
    return "Round and orange";
  case Enum::Apple:
    return "APPLE" ;

  default:
    return "Not recognized..";
  }
}

Is there a better or recognized idiom for doing this?

这样做有更好的或公认的习语吗?

采纳答案by Mark Ransom

enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };

const char * getTextForEnum( int enumVal )
{
  return EnumStrings[enumVal];
}

回答by Blagovest Buyukliev

Kind of an anonymous lookup table rather than a long switch statement:

一种匿名查找表而不是长 switch 语句:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];

回答by nathan

You could throw the enum value and string into an STL map. Then you could use it like so.

您可以将枚举值和字符串放入 STL 映射中。然后你可以像这样使用它。

   return myStringMap[Enum::Apple];