将枚举声明为变量时出错

时间:2011-07-27 07:45:57

标签: c++ enums

我有以下语法:

enum home
{
no,
yes,
}homew;

home homes;

std::string s;
s="no";

homes=s; //is not working. Why?

我错了吗?

6 个答案:

答案 0 :(得分:1)

您将字符串与枚举值混淆。

enum变量只是一个整数,你可以在编译时使用文字,只不过是。

它使代码更易于理解和自我记录,而不仅仅是使用数字文字。

答案 1 :(得分:1)

  1. 这个

    enum home { no, yes, } homew;
    

    定义 类型 home以及该类型的 变量 homew
    你有意吗?为什么?

  2. enum类型定义的值是文字,可以这样使用:

    home homes = no;
    
  3. 在C ++中,没有内置的方法来在枚举值文字和它们的字符串表示之间进行转换。如果您需要,则必须cook up your own

答案 2 :(得分:0)

C ++中的

枚举隐式为int数据类型。您不能将字符串值分配给枚举。

答案 3 :(得分:0)

它无法编译,因为C ++没有提供从std::string转换为enum的内置机制。

答案 4 :(得分:0)

typeof(home) != typeof(std::string) // types are not equal

因此,您无法将enum分配给std::string或其他方式。然而,enumboolint等整数类型之间的隐式转换是可能的。

  

有没有办法解决我的问题呢?

如果可能,请使用std::map

std::map<std::string, home> myTypes;
myTypes["yes"] = yes;
myTypes["no"] = no;

现在你可以做到,

homes = myTypes["no"];

答案 5 :(得分:0)

正如其他人所指出的,枚举值为int类型。你可以编写一个小函数,从枚举转换为String,如下所示:

std::string GetStringFromEnum(home iHome)
{
 switch (home)
 {
  case yes: return "yes";
  case no: return "no"; break;
  default: return "here be dragons";
 }
}

反之亦然:

home GetEnumFromString(std::string iImput)
{
 if (iImput == "yes") return yes;
 return no; //if you extend the enum beyond 2 values, this function will get more complicated
}

您可以像这样修改代码:

homes = GetStringFromEnum(no)

这种方法的缺点是,如果你修改枚举,你还必须修改转换函数。

HTH,
JP

相关问题