c++ - 为什么枚举类比普通枚举更受欢迎?

标签 c++ class enums c++-faq

我听说有人推荐在 C++ 中使用枚举,因为它们的类型安全

但这究竟意味着什么?

最佳答案

C++有两种enum:

  1. 枚举类es
  2. 普通的枚举s

这里有几个关于如何声明它们的示例:

 enum class Color { red, green, blue }; // enum class
 enum Animal { dog, cat, bird, human }; // plain enum 

两者有什么区别?

  • enum classes - 枚举器名称是枚举的本地,它们的值不会隐式转换为其他类型(例如另一个 enumint)

  • Plain enums - 其中枚举器名称与枚举及其所在的范围相同 值隐式转换为整数和其他类型

例子:

enum Color { red, green, blue };                    // plain enum 
enum Card { red_card, green_card, yellow_card };    // another plain enum 
enum class Animal { dog, deer, cat, bird, human };  // enum class
enum class Mammal { kangaroo, deer, human };        // another enum class

void fun() {

    // examples of bad use of plain enums:
    Color color = Color::red;
    Card card = Card::green_card;

    int num = color;    // no problem

    if (color == Card::red_card) // no problem (bad)
        cout << "bad" << endl;

    if (card == Color::green)   // no problem (bad)
        cout << "bad" << endl;

    // examples of good use of enum classes (safe)
    Animal a = Animal::deer;
    Mammal m = Mammal::deer;

    int num2 = a;   // error
    if (m == a)         // error (good)
        cout << "bad" << endl;

    if (a == Mammal::deer) // error (good)
        cout << "bad" << endl;

}

结论:

enum classes 应该是首选,因为它们会减少可能导致错误的意外。

关于c++ - 为什么枚举类比普通枚举更受欢迎?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18335861/

相关文章:

c++ - Qt中的预编译头避免重新编译修改后的头文件

java - 如何从java中的另一个类更新jLabel或setText?

c++ - Rcpp 编译属性不可调用

c++ - 我的 SWIG 类型映射出了什么问题?

C# 基于另一个属性值的不同属性

java - Switch 语句中的 PowerMockito 枚举抛出 NPE

mysql - 向现有表添加新的枚举列

c++ - 继承只是为了共享枚举 - 危险吗?

python - 我可以使用 pybind11 将 numpy 数组传递给接受 Eigen::Tensor 的函数吗?

java - 类实例化与通过引用检索