Ole*_*siy 420
C++有两种enum
:
enum class
ESenum
小号以下是如何声明它们的几个示例:
enum class Color { red, green, blue }; // enum class
enum Animal { dog, cat, bird, human }; // plain enum
Run Code Online (Sandbox Code Playgroud)
两个有什么区别?
enum class
es - 枚举器名称是枚举的本地名称,它们的值不会隐式转换为其他类型(如另一个enum
或类似int
)
Plain enum
s - 枚举器名称与枚举的范围相同,其值隐式转换为整数和其他类型
例:
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;
}
Run Code Online (Sandbox Code Playgroud)
enum class
es应该是首选,因为它们可以减少可能导致错误的意外.
Pap*_*ter 224
来自Bjarne Stroustrup的C++ 11 FAQ:
在
enum class
ES("新枚举","强枚举")解决三个问题,与传统的C++枚举:
- 常规枚举隐式转换为int,当有人不希望枚举充当整数时会导致错误.
- 常规枚举将其枚举器导出到周围的范围,导致名称冲突.
enum
无法指定a 的基础类型,导致混淆,兼容性问题,并且无法进行前向声明.新的枚举是"枚举类",因为它们将传统枚举(名称值)的各个方面与类的方面(作用域成员和缺少转换)结合起来.
因此,正如其他用户所提到的,"强大的枚举"会使代码更安全.
"经典"的基础类型enum
应该是一个足够大的整数类型,以适应所有的值enum
; 这通常是一个int
.此外,每个枚举类型应与char
有符号/无符号整数类型兼容.
这是对enum
底层类型必须是什么的广泛描述,因此每个编译器将自己决定经典的基础类型,enum
有时结果可能会令人惊讶.
例如,我已经看过这样的代码了很多次:
enum E_MY_FAVOURITE_FRUITS
{
E_APPLE = 0x01,
E_WATERMELON = 0x02,
E_COCONUT = 0x04,
E_STRAWBERRY = 0x08,
E_CHERRY = 0x10,
E_PINEAPPLE = 0x20,
E_BANANA = 0x40,
E_MANGO = 0x80,
E_MY_FAVOURITE_FRUITS_FORCE8 = 0xFF // 'Force' 8bits, how can you tell?
};
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,一些天真的编码器认为编译器会将E_MY_FAVOURITE_FRUITS
值存储到无符号的8位类型......但是对它没有任何保证:编译器可以选择unsigned char
或者,int
或者short
,任何这些类型都足够大以适应所有在...中看到的价值观enum
.添加字段E_MY_FAVOURITE_FRUITS_FORCE8
是一种负担,并不会强制编译器对基础类型做出任何选择enum
.
如果某些代码依赖于类型大小和/或假设它E_MY_FAVOURITE_FRUITS
具有某种宽度(例如:序列化例程),则此代码可能会以一些奇怪的方式运行,具体取决于编译器的想法.
更糟糕的是,如果一些同事不小心为我们增加了新的价值enum
:
E_DEVIL_FRUIT = 0x100, // New fruit, with value greater than 8bits
Run Code Online (Sandbox Code Playgroud)
编译器不会抱怨它!它只是调整类型的大小以适应所有的值enum
(假设编译器使用尽可能小的类型,这是我们不能做的假设).这种简单而粗心的补充enum
可能会破坏相关代码.
由于C++ 11可以指定基础类型enum
和enum class
(感谢rdb)所以这个问题得到了很好的解决:
enum class E_MY_FAVOURITE_FRUITS : unsigned char
{
E_APPLE = 0x01,
E_WATERMELON = 0x02,
E_COCONUT = 0x04,
E_STRAWBERRY = 0x08,
E_CHERRY = 0x10,
E_PINEAPPLE = 0x20,
E_BANANA = 0x40,
E_MANGO = 0x80,
E_DEVIL_FRUIT = 0x100, // Warning!: constant value truncated
};
Run Code Online (Sandbox Code Playgroud)
如果字段的表达式超出此类型的范围,则指定基础类型,编译器将抱怨而不是更改基础类型.
我认为这是一个很好的安全改进.
那么为什么enum类优于普通枚举?,如果我们可以选择scoped(enum class
)和unscoped(enum
)枚举的基础类型,还有什么可以做出enum class
更好的选择?:
int
.Sak*_*ham 44
使用枚举类优于普通枚举的基本优点是,您可以为2个不同的枚举使用相同的枚举变量,并且仍然可以解析它们(OP 已将其称为类型安全)
例如:
enum class Color1 { red, green, blue }; //this will compile
enum class Color2 { red, green, blue };
enum Color1 { red, green, blue }; //this will not compile
enum Color2 { red, green, blue };
Run Code Online (Sandbox Code Playgroud)
至于基本枚举,编译器将无法区分red
是引用类型Color1
还是Color2
在hte下面的语句中.
enum Color1 { red, green, blue };
enum Color2 { red, green, blue };
int x = red; //Compile time error(which red are you refering to??)
Run Code Online (Sandbox Code Playgroud)
小智 19
枚举用于表示一组整数值.
在class
后关键字enum
指定该枚举是强类型和枚举的作用域.这样,enum
类可以防止意外误用常量.
例如:
enum class Animal{Dog, Cat, Tiger};
enum class Pets{Dog, Parrot};
Run Code Online (Sandbox Code Playgroud)
在这里,我们不能混合动物和宠物的价值观.
Animal a = Dog; // Error: which DOG?
Animal a = Pets::Dog // Pets::Dog is not an Animal
Run Code Online (Sandbox Code Playgroud)
Tom*_* VH 11
值得注意的是,除了这些其他答案之外,C++20 解决了其中一个问题enum class
:冗长。想象一个假设enum class
,Color
。
void foo(Color c)
switch (c) {
case Color::Red: ...;
case Color::Green: ...;
case Color::Blue: ...;
// etc
}
}
Run Code Online (Sandbox Code Playgroud)
与普通enum
变体相比,这是冗长的,其中名称在全局范围内,因此不需要以Color::
.
但是,在 C++20 中,我们可以使用using enum
将枚举中的所有名称引入当前作用域,从而解决问题。
void foo(Color c)
using enum Color;
switch (c) {
case Red: ...;
case Green: ...;
case Blue: ...;
// etc
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在,没有理由不使用enum class
.
C ++ 11常见问题解答提到以下几点:
传统的枚举隐式转换为int,当某人不希望枚举充当整数时会导致错误。
enum color
{
Red,
Green,
Yellow
};
enum class NewColor
{
Red_1,
Green_1,
Yellow_1
};
int main()
{
//! Implicit conversion is possible
int i = Red;
//! Need enum class name followed by access specifier. Ex: NewColor::Red_1
int j = Red_1; // error C2065: 'Red_1': undeclared identifier
//! Implicit converison is not possible. Solution Ex: int k = (int)NewColor::Red_1;
int k = NewColor::Red_1; // error C2440: 'initializing': cannot convert from 'NewColor' to 'int'
return 0;
}
Run Code Online (Sandbox Code Playgroud)
传统的枚举将其枚举数导出到周围的范围,从而引起名称冲突。
// Header.h
enum vehicle
{
Car,
Bus,
Bike,
Autorickshow
};
enum FourWheeler
{
Car, // error C2365: 'Car': redefinition; previous definition was 'enumerator'
SmallBus
};
enum class Editor
{
vim,
eclipes,
VisualStudio
};
enum class CppEditor
{
eclipes, // No error of redefinitions
VisualStudio, // No error of redefinitions
QtCreator
};
Run Code Online (Sandbox Code Playgroud)
枚举的基础类型无法指定,从而导致混乱,兼容性问题,并使前向声明变得不可能。
// Header1.h
#include <iostream>
using namespace std;
enum class Port : unsigned char; // Forward declare
class MyClass
{
public:
void PrintPort(enum class Port p);
};
void MyClass::PrintPort(enum class Port p)
{
cout << (int)p << endl;
}
Run Code Online (Sandbox Code Playgroud)
。
// Header.h
enum class Port : unsigned char // Declare enum type explicitly
{
PORT_1 = 0x01,
PORT_2 = 0x02,
PORT_3 = 0x04
};
Run Code Online (Sandbox Code Playgroud)
。
// Source.cpp
#include "Header1.h"
#include "Header.h"
using namespace std;
int main()
{
MyClass m;
m.PrintPort(Port::PORT_1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尚未明确提及的一件事 - 作用域功能为您提供了一个选项,使枚举和类方法具有相同的名称。例如:
class Test
{
public:
// these call ProcessCommand() internally
void TakeSnapshot();
void RestoreSnapshot();
private:
enum class Command // wouldn't be possible without 'class'
{
TakeSnapshot,
RestoreSnapshot
};
void ProcessCommand(Command cmd); // signal the other thread or whatever
};
Run Code Online (Sandbox Code Playgroud)