C++: enum

Yao Yao on March 19, 2015

整理自 Thinking in C++。没啥特别好说的。

1. 起手式

enum ShapeType {

int main() {
	ShapeType shape = circle;

	switch(shape) {
		case circle: /* circle stuff */ break;
		case square: /* square stuff */ break;
		case rectangle: /* rectangle stuff */ break;
  • enum 就不需要 typedef 了
  • enum 值的本质是 int,所以可以用在 switch
  • enum 的默认赋值是 0,1,2…

2. 自赋值式

enum ShapeType {
	circle = 10, square = 20, rectangle = 50

如果前一个 enum 值有赋值,其后的一个没有赋值,那么后面这个 enum 值自动设置为前面的值+1:

#include <iostream>
using namespace std;

enum ShapeType {
	circle = 10, square, rectangle = 50

int main() {
	cout << square; // output: 11

3. C++ 比 C 加强了对 enum 的类型检查

虽然 enum 值的本质是 int,但 C++ 还是做了些工作的,比如 C 里可以 Color a = blue + 1;,C++ 就是不允许的,理由是:

This is because incrementing an enumeration is performing two type conversions, one of them legal in C++ and one of them illegal. First, the value of the enumeration is implicitly cast from a color to an int, then the value is incremented, then the int is cast back into a color. In C++ this isn’t allowed, because color is a distinct type and not equivalent to an int. This makes sense, because how do you know the increment of blue will even be in the list of colors?


4. Scoped Enumerations

  • 来自 C++ Primer, 5th Edition

C++11 introduced scoped enumerations. We define a scoped enumeration using the keywords enum class or, equivalently, enum struct. 如果只有一个单纯的 enum,则是 unscoped enumeration

The names of the enumerators in a scoped enumeration follow normal scoping rules and are inaccessible outside the scope of the enumeration. The enumerator names in an unscoped enumeration are placed into the same scope as the enumeration itself:

enum color {red, yellow, green};			// OK. unscoped enumeration
enum stoplight {red, yellow, green};		// ERROR. redefines enumerators
enum class peppers {red, yellow, green};	// OK. scoped enumeration

color eyes = green; // OK. enumerators are in scope for an unscoped enumeration
peppers p = green;	// ERROR. enumerators from peppers are not in scope
					// color::green is in scope but has the wrong type

color hair = color::red;	// OK. we can explicitly access the enumerators
peppers p2 = peppers::red;	// OK. using red from peppers

blog comments powered by Disqus