【发布时间】:2011-07-27 07:45:57
【问题描述】:
我有以下语法:
enum home
{
no,
yes,
}homew;
home homes;
std::string s;
s="no";
homes=s; //is not working. Why?
我错了吗?
【问题讨论】:
-
请不要对我们大喊大叫 (:
我有以下语法:
enum home
{
no,
yes,
}homew;
home homes;
std::string s;
s="no";
homes=s; //is not working. Why?
我错了吗?
【问题讨论】:
您将字符串与枚举值混淆了。
enum 变量只是一个整数,您可以在编译时使用文字,仅此而已。
它使代码更易于理解和自我记录,而不仅仅是使用数字文字。
【讨论】:
homes = yes或homes = no。
这个
enum home { no, yes, } homew;
定义类型 home 加上该类型的变量 homew。
你是故意的吗?为什么?
为enum 类型定义的值是文字,可以这样使用:
home homes = no;
在 C++ 中,没有内置方法可以在枚举值文字和它们的字符串表示之间进行转换。如果你需要这个,你必须cook up your own。
【讨论】:
C++ 中的枚举是隐式的int 数据类型。您不能将字符串值分配给枚举。
【讨论】:
它无法编译,因为 C++ 没有提供将 std::string 转换为 enum 的内置机制。
【讨论】:
typeof(home) != typeof(std::string) // types are not equal
因此,您不能将enum 分配给std::string 或其他方式。但是,enum 和 bool、int 等整数类型之间的隐式转换是可能的。
有什么方法可以解决我的问题吗?
如果可能,请使用std::map。
std::map<std::string, home> myTypes;
myTypes["yes"] = yes;
myTypes["no"] = no;
现在可以了,
homes = myTypes["no"];
【讨论】:
std::map<key,value>;它本身就是一个容器类,如std::string。你可以使用这个容器来关联你的string(key) 和enum(value)。
#include <map>;只需参考我发布的链接中的示例即可。
正如其他人指出的,枚举值是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,
日本
【讨论】: