c++ - 为什么枚举会隐式转换为 std::string?

标签 c++ enums

很抱歉,如果之前有人问过这个问题,或者如果我在代码中做错了什么,但我刚刚遇到了一个错误,我分配了一个错误的变量并且它沸腾了这个例子:

#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/

相关文章:

c++ - 如何在可能是任何类的属性的 void 函数上创建 typedef?

c++ - 如何从另一张 map 构建一张 map ?

c++ - 寻找滥用枚举的替代方法

java - EnumSet 'and' 操作

c++ - QList 清除函数调用是否清除存储在 QList 中的动态分配对象的内存?

c++ - astyle格式化多行<<

c++ - 将任何类的任何成员函数作为回调函数传递

machine-learning - h2o 流用户界面 : Build Model but no ROC CURVE or AUC for multiclass?

java - 在 Java 中使用枚举来专门化模板

java - 未找到字段导致的 LibGDX SerializationException