为什么枚举类比纯枚举优先? [英] Why is enum class preferred over plain enum?

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

问题描述

我听说有少数人因为类型安全而建议在C ++中使用枚举类。

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

但这是什么意思?

推荐答案

类型:


  1. 枚举类 es

  2. 平常枚举 s

  1. enum classes
  2. Plain enums

这里是一些例子如何声明他们:

Here are a couple of examples how to declare them:

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

两者之间有什么区别?


  • 枚举类 es - 枚举器名称 local 到枚举和它们的值不会隐式转换为其他类型(像另一个枚举 int

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

普通枚举 s - 其中枚举器名称与枚举属于相同的范围,其
值隐式转换为整数和其他类型

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;

}



结论:



枚举类应该是首选,因为它们会导致更少的惊喜,可能导致错误。

Conclusion:

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

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

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