我可能缺少某些东西,但我正在使用一个代码库,它使用了很多
typedef enum foo
{
....
} foo;
这只是普通的枚举类,不具备强类型的特性吗?
我可能缺少某些东西,但我正在使用一个代码库,它使用了很多
typedef enum foo
{
....
} foo;
typedef enum
和enum class
的使用有所不同。
正如评论中@UnholySheep提到的那样,typedef enum
的使用大多是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
)版本的代码定义了一个Ghost
,那么只需使用Ghost myGhost;
即可。因此,在C++中使用typedef enum
的原因并不多。
这与enum class
有很大不同。在C++中,enum class
的优点是枚举中定义的常量不会成为定义enum
的命名空间的一部分,并且不能从enum class
隐式地转换为整数类型。因此,enum class
主要是为了类型安全和防止在使用enum
时犯错误。
希望这能帮到您!