enum 与 enum class


c++11中引入了新的枚举类型---->强制枚举类型

// unscoped enum: enum [identifier] [: type]
{enum-list};  // scoped enum: enum [class|struct] [identifier] [: type] 
{enum-list};
  identifier: 指定给与枚举的类型名称。
   type: 枚举器的基础类型(默认int),所有枚举器都具有相同的基础类型,可能是任何整型。
   enum-list: 枚举中以逗号分隔的枚举器列表。 范围中的每个枚举器或变量名必须是唯一的。 但是,值可以重复。 在未区分范围的枚举中,范围是周边范围;在区分范围的枚举中,范围是 enum-list 本身。
   class: 可使用声明中的此关键字指定枚举区分范围,并且必须提供 identifier。 还可使用 struct 关键字来代替 class,因为在此上下文中它们在语义上等效。


如下为两者的简单示例:
enum Test
{
  test1,
  test2
};

int a = test1;  // 类型隐式转换,枚举常量无须限定
if (test1 == 0)
  cout << "Hello world.";



enum class ErrorCode
{
  ERROR_ONE,
  ERROR_TWO,
  ERROR_THREE
};

int num = 2;
num = static_cast<int>(ErrorCode::ERROR_ONE); // 类型需要显示转换,而且枚举常量必须限定
ErrorCode test = static_cast<ErrorCode>(12);  // 其实这个整数已经超出范围了,但是居然合法
if (test == ErrorCode::ERROR_THREE)
  cout << "It's impossible"


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM