【问题标题】:What's the difference between typedef enum and enum class?typedef 枚举和枚举类有什么区别?
【发布时间】:2020-07-03 22:38:37
【问题描述】:

我可能遗漏了一些东西,但我正在使用一个使用大量的代码库

typedef enum foo
{
    ....
} foo;

这是否与枚举类相同但不是强类型?

【问题讨论】:

标签: c++ enums typedef enum-class


【解决方案1】:

使用typedef enum 的作用与enum class 不同。

typedef enum 的使用,正如 cmets 中提到的 @UnholySheep,主要是 C++ 中不需要的 C 习惯用法。在 C 中,如果您像这样声明 enum:

enum Ghost {
    Blinky,
    Pinky,
    Inky,
    Clyde
};

那么要声明一个Ghost 类型的变量,你必须说

enum Ghost oneGhost;

这里使用“enum”可能有点烦人,所以出现了一种将enum声明写成的模式

typedef enum Ghost {
    Blinky,
    Winky,
    Pinky,
    Clyde
} Ghost;

这表示“像往常一样定义了一个名为 enum Ghost 的类型,但您可以简称为 Ghost。这样,在 C 中,您可以编写

Ghost myGhost;

并拥有您需要的一切。

但是,C++ 放弃了以这种方式使用enum 的要求。如果您使用代码的第一个(typedef-free)版本定义了Ghost,您可以直接说Ghost myGhost;。从这个意义上说,没有太多理由在 C++ 中使用typedef enum。

这与enum class 完全不同。在 C++ 中,enum class 的优点是枚举中定义的常量不会最终成为定义 enum 的命名空间的一部分,并且您不能从 enum class 隐式转换为整数类型。从这个意义上说,enum class 主要是关于类型安全性,使enum 很难出错。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 1970-01-01
    • 2011-02-13
    • 2013-10-27
    • 2016-01-02
    • 2018-09-25
    • 2014-09-07
    • 1970-01-01
    相关资源
    最近更新 更多