c++11 枚举enum

文章介绍了C++11对enum的两个新特性:一是可以限制枚举变量的值大小,例如通过`enumDEV_TYPE:unsignedchar`限制最大值;二是引入了枚举类(enumclass),这可以限制枚举的作用域,避免命名冲突。通过枚举类,可以更安全地使用枚举,比如在示例中防止了与全局变量red的冲突。

        看到 c++11 中 enum 的两个新用法,记录一下。

1,限制枚举变量值大小

#include <stdio.h>
#include <stdlib.h>

enum DEV_TYPE: unsigned char
{
    DEV_A,
    DEV_B,
    DEV_C,
    DEV_D = 255
};

int main()
{
    return 0;
}

类似于 class 中的继承的语法,这里的作用是限制了 enum 元素的最大值,如上 DEV_D 的最大值就是 255,如果赋值大于 255 会怎样呢?

#include <stdio.h>
#include <stdlib.h>

enum DEV_TYPE: unsigned char
{
    DEV_A,
    DEV_B,
    DEV_C,
    DEV_D = 256
};

int main()
{
    return 0;
}

编译失败: 

2,枚举类

#include <stdio.h>
#include <stdlib.h>

enum class COLOR
{
    white,
    red,
    black,
    gray,
    green
};

int main()
{
    return 0;
}

这样用有什么好处----限制了枚举的变量的作用域。如果没有这个作用域是怎样的呢?如:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    enum COLOR
    {
        white,
        red,
        black,
        gray,
        green
    };

    bool red = true;
    return 0;
}

编译错误,因为这个main作用域内已经有了一个枚举类型值 red。改用枚举类就不一样了:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    enum class COLOR 
    {
        white,
        red,
        black,
        gray,
        green
    };

    bool red = true;

    //使用域限定符
    COLOR color = COLOR::red;
    
    return 0;
}

有了枚举类限定了枚举类型的作用域,减少了命名空间的冲突。 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值