为什么枚举类比普通枚举更受欢迎? [英] Why is enum class preferred over plain enum?

查看:28
本文介绍了为什么枚举类比普通枚举更受欢迎?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I heard a few people recommending to use enum classes in C++ because of their type safety.

但这到底是什么意思?

推荐答案

C++有两种enum:

  1. 枚举类es
  2. 普通enums

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

Here are a couple of examples on how to declare them:

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

两者有什么区别?

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

  • enum classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum or int)

Plain enums - 其中枚举器名称与枚举及其值隐式转换为整数和其他类型

Plain enums - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types

示例:

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 应该是首选,因为它们引起的意外更少,可能导致错误.

Conclusion:

enum classes should be preferred because they cause fewer surprises that could potentially lead to bugs.

这篇关于为什么枚举类比普通枚举更受欢迎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆