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

// unscoped enum:
enum [identifier] [: type]
{enum-list}; 

// scoped enum:
enum [class|struct] [identifier] [: type] 
{enum-list};
  identifier:指定给与枚举的类型名称。
  type:可能是任何整型。
enum-list 本身。
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"

相关文章:

  • 2021-11-25
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-19
  • 2021-12-13
  • 2022-02-03
  • 2022-12-23
  • 2022-12-23
  • 2021-11-26
相关资源
相似解决方案