【c++11】 enum class: 强类型枚举

#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    // 1、枚举类型的定义:
    // 普通枚举常量作用域提升至外围(main函数之内)并且可以整型提升
    enum Numbers {One=1, Two, Three};    
    // 强类型枚举常量的作用域仅限于Options类型之内,即{}之内; 并且不进行整型提升
    // "One"虽然同名,但由于作用域不同,并不会名字冲突 
    // 关键字:enum class,位置不能交换
    enum class Options {None, One, All=15}; 

    // 2、普通枚举的名字冲突
    {
        enum Numbers {One, Two, Three};    
//      enum Options {None, One, All}; // error! 名字冲突:"One"重定义
//      int i = One;
    }

    // 3、枚举常量的整型提升
    int i = One;        // ok! Numbers's One, i=1
    i += Three;            // ok!
//  i = Options::One;    // error! 强类型枚举常量并不能整型提升
    i = static_cast<int>(Options::One); // ok! i=1

    // 4、枚举变量的定义初始化
    Numbers n;
    n = One;
    n = Numbers::One;
//  n += 1;             // error!
//  n = All;            // error! All不在作用域中,并且类型不匹配
//  n = Options::One;   // error! 试图赋值Options类型的One,类型不匹配
    Options o;
//  o = One;    // error! 试图赋值Numbers类型的One,类型不匹配
//  o = All;    // error! Options类型之All不在作用域范围
    o = Options::One;        // ok! 必须使用作用域操作符来访问强类型枚举常量
    o = Options::All;        // ok!

    // 5、在判断语句中的枚举值
    if(One<3){}              // ok!
    if(n==1){}               // ok!
    if(n<Three){}            // ok!
    if(One<Three){}          // ok!
    if(Options::All>Options::One){} // ok! if is true!
    if(o==Options::All){}           // ok! if is true!
//  if(Options::All>10){}    // error!

    // 6、指定枚举类的底层类型(枚举常量类型),默认时至少为int
    enum Enum1: unsigned int{first, second, third};
    enum class Enum2: char{first, second, third};
    enum Enum3: unsigned int{Red=-6, Blue, Yellow}; // warning C4369: “Red”: 枚举数的值“-6”不能表示为“unsigned int”,值是“4294967290”
    std::cout << Red << std::endl;
    enum class Enum4: char{first=10086, second, third}; // warning C4369: “first”: 枚举数的值“10086”不能表示为“char”,值是“102”
//  std::cout << Enum4::second << std::endl; // error! 强类型枚举Enum4没有此操作,second不是整型
    std::cout << (char)Enum4::second << std::endl;
//  enum class Enum4: double{Red=-6, Blue, Yellow}; //error:!“double”: 枚举的基础类型非法,不是整型

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值