modern effective c++ Item10: unscoped enum和scoped enum

Modern Effective C++ Item10:

  • 什么是unscoped enum和scoped enum?
  • 推荐使用scoped enum的原因…

10.1 什么是unscoped enum? Scoped enum?

      在C++11之前,使用枚举的方式是这样的,

enum Color { black, white, red};
auto white = flase;  // error, variable already exits in this scope

      枚举中的值的作用域不是在括号内,而是和Color的作用域是一样的。因此这些enum的成员已经泄露到了enum所在的作用域去了,官方称之为unscoped.
      在C++11之后,与之对应的版本为scoped enum,如下

enum class Color { black, white, red};
auto white =false;  //可以的
Color c = Color::red;

      因为scoped enum通过enum class声明,因此也叫做enum class.

10.2 推荐使用scoped enum的原因?

      根据modern effective c++ item10,根据这一节可以得出,倾向于选择scoped enum,相比于unscoped enum,有以下优点:

  • 上面所描述的一点是scoped enum中枚举中的变量不会泄露出来,从而较少对命名命名空间的污染.
  • scoped enum中的成员为强类类型,不会隐式转换.
enum Color { black, white, red};
Color c = red;
if(c > 3.4) { cout <<“c> 3.4<<endl;}  // implicit conversion

      上面的枚举变量可以隐式转换为int,然后从数值类型转换为浮点类型,和3.4进行比较。
      但是scoped enum如果需要转换到不同的类型,需要使用cast把Color转换为需要的类型。

enum Color { black, white, red};
double c = static_cast<double>(Color::red);
if (c > 3.4) { cout<< “c>3.4<<endl;}  // need to cast manually
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章