enum options {Yes,No};
class A{
int i;
string str;
options opt;
};
int main{
A obj;
obj.i=5;
obj.str="fine";
obj.opt="Yes"; // compiler error
}
如何将
const char *
赋值给 opt?enum options {Yes,No};
class A{
int i;
string str;
options opt;
};
int main{
A obj;
obj.i=5;
obj.str="fine";
obj.opt="Yes"; // compiler error
}
const char *
赋值给 opt?只需这样做
obj.opt=Yes;
这段代码:
obj.opt="Yes";
尝试将字符串字面值(完全不同的类型)分配给枚举类型,C++不会自动转换。namespace options
{
enum Enum {Yes,No,Invalid};
Enum FromString(const std::string& str);
// might also add ToString, ToInt, FromInt to help with conversions
}
Enum FromString(const std::string& str)
{
if (str == "Yes")
{
return Yes
}
else if (str == "No")
{
return No;
}
return Invalid; //optionally throw exception
}
现在你可以这样做:
class A{
int i;
string str;
options::Enum opt; // notice change here
};
...
obj.opt=options::FromString("Yes");
所以你可以看到,在C++中,枚举类型可能不像其他语言中的枚举类型那样功能齐全。您需要手动进行转换。因为枚举值不是字符串。以下写法是正确的:
int main{
A obj;
obj.opt=Yes;
}
枚举不是字符串,而只是值
obj.opt = Yes;
你不能这样做。你必须使用一些字符串比较并设置它。
const char*
。您需要做的就是创建宏。
例如:
#define ENUM_TO_CSTR(x) #x
然后:
obj.opt=ENUM_TO_CSTR(Yes)
。int x = 10; cout << ENUM_TO_CSTR(x) << endl;
将在屏幕上打印x
(而不是10
),因此在使用时要小心! obj.opt = Yes;
尝试从 obj 中打印 opt 的值:
cout << obj.opt;
由于枚举索引从0开始,因此您将获得输出为0。是为0,否为1。