很抱歉,如果之前有人问过这个问题,或者如果我在代码中做错了什么,但我刚刚遇到了一个错误,我分配了一个错误的变量并且它沸腾了这个例子:
#include <string>
enum Enum {
A, B, C
};
int main() {
std::string s = "A";
if (s == "A")
s = A;
else if (s == "B")
s = B;
else if (s == "C")
s = C;
printf ("%s\n", s.c_str());
return 0;
}
请注意,在 if/else if 语句中,我将赋值给变量 s(实际示例是将“mode”转换为“mode_”,其中一个是字符串,一个是枚举,我在一个中省略了下划线案例。
我的问题是,为什么编译器没有报错?即使使用 -Wall 和 -W,它也会默默地成功。
我觉得我遗漏了什么,或者是我的编译器出了问题?标准中有这方面的内容吗?
最佳答案
标准库包含原型(prototype)
basic_string& operator=(charT c);
这意味着您可以将单个字符分配给字符串:
s = 'A';
但是单个字符只是一个小整数,不是吗?
您可以使用 C++11 风格的作用域枚举器避免这个问题。以下将产生预期的编译器错误:
#include <string>
enum class Enum {
A, B, C
};
int main() {
std::string s = "A";
if (s == "A")
s = Enum::A;
else if (s == "B")
s = Enum::B;
else if (s == "C")
s = Enum::C;
printf ("%s\n", s.c_str());
return 0;
}
关于c++ - 为什么枚举会隐式转换为 std::string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23924062/