枚举类(“新枚举”,“强枚举”)解决三个问题,与传统的C++枚举:
- 传统
enums
隐式转换为int
,导致错误,当有人不希望的枚举作为一个整数。
- 传统
enums
将他们的统计员输出到周围的范围,导致姓名冲突。
- 无法指定
enum
的基础类型,导致混淆,兼容性问题,并且使前向声明变得不可能。
enum class
(“强枚举”)是强类型和范围的:
enum Alert { green, yellow, orange, red }; // traditional enum
enum class Color { red, blue }; // scoped and strongly typed enum
// no export of enumerator names into enclosing scope
// no implicit conversion to int
enum class TrafficLight { red, yellow, green };
Alert a = 7; // error (as ever in C++)
Color c = 7; // error: no int->Color conversion
int a2 = red; // ok: Alert->int conversion
int a3 = Alert::red; // error in C++98; ok in C++11
int a4 = blue; // error: blue not in scope
int a5 = Color::blue; // error: not Color->int conversion
Color a6 = Color::blue; // ok
如图所示,传统枚举照常上班,但你现在可以选择用枚举的名字资格。
新的枚举类型是“枚举类”,因为它们将传统枚举(名称值)的方面与类的方面(作用域成员和没有转换)相结合。
能够指定的基本类型允许枚举的简单的互操作性和保证尺寸:枚举
enum class Color : char { red, blue }; // compact representation
enum class TrafficLight { red, yellow, green }; // by default, the underlying type is int
enum E { E1 = 1, E2 = 2, Ebig = 0xFFFFFFF0U }; // how big is an E?
// (whatever the old rules say;
// i.e. "implementation defined")
enum EE : unsigned long { EE1 = 1, EE2 = 2, EEbig = 0xFFFFFFF0U }; // now we can be specific
这也使前向声明:
enum class Color_code : char; // (forward) declaration
void foobar(Color_code* p); // use of forward declaration
// ...
enum class Color_code : char { red, yellow, green, blue }; // definition
基础类型必须是一个有符号或无符号整数类型;默认为int
。
在标准库,enum
类用于:
- 映射系统特定的错误代码:在
<system_error>
:enum class errc
;
- 指针安全指标:
<memory>
:enum class pointer_safety { relaxed, preferred, strict };
- I/O流误区:
<iosfwd>
:enum class io_errc { stream = 1 };
- 异步通讯错误处理:在
<future>
:enum class future_errc { broken_promise, future_already_retrieved, promise_already_satisfied };
其中几个已运营商,如==
定义。
您是否曾浏览[wikipedia](http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations)? – Nobody
@Nobody:是的,我看过'wiki',但无法理解如何使用它,以及有什么好处。 –