C++ 强枚举类型

为了解决c/c++中的enum类型的一系列缺点,比如:非强类型,允许隐式转换为int型,占用存储空间及符号性不确定。c++11引入了枚举类(又称为:强枚举类型strong-typed enum)

语法格式:

enum class 类型名 {枚举值表}; 

如:enum class People{yellow,black,white};

//这样就成功的定义了一个强类型的枚举People。

注意:等价于 enum struct 类型名{枚举值表};
(enum class中的成员没有公有私有之分,也不会使用
模板来支持泛化的功能)

3.1 强类型的枚举优点
(1)强作用域:强类型的枚举成员的名称不会被输出到其父作用域空间;
(2)转换限制:强类型枚举成员的值不可以与int隐式的相互转换。
(3)可以指定底层类型。强类型枚举底层类型为int,但是也可以显示的指定底层类型。具体方法:在enum名称后面加:“:type”,其中type可以是除wchar_t以外的任何int,如下:

enum class People:type char{yellow,black,white};
//指定了People为基于char的强枚举类型。

示例3中详细说明强枚举的特点:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

enum class Color
{
    red,
    orange,
    yellow,
    green,
    blue,
    cyan,
    purple

};

enum class Apple
{
    green = 1,
    red,
};

int main(int argc,char **argv)
{
    enum Apple apple = Apple::green;
    apple = red; //编译失败,必须使用强类型名称; ‘red’ was not declared in this scope
    if(apple == Color::red) //编译失败,必须使用Apple::red; no match for ‘operator==’ (operand types are ‘Apple’ and ‘Color’)
    {
       printf("The color of apple is red.\n");
    }
    if(apple == Apple::red)	//编译通过
    {
        printf("The color of apple is red.\n");
    }

    if(apple > 1)   //编译失败,无法隐式转换为int类型;error: no match for ‘operator>’ (operand types are ‘Apple’ and ‘int’)
    {
        cout<<"apple is greater than 1."<<endl;
    }
    
    if((int)apple > 1)	//编译通过,显示的类型转换
    {
        cout<<"apple is greater than 1."<<endl;
    }
    return 0;
}

4 . c++11对enum类型进行了扩展
主要有2个:
(1)对于底层的基本类型;这个参考前面的“强类型的优点(3)
(2)对于其作用域的扩展。在c++11中,枚举成员的名字除了会自动输出到父作用域,也可以在枚举类型定义的作用域内有效。

示例4:

enum Color{red,yellow,green,black,white};
enum Color color = red;
color = yellow;
color = Color::yellow;
//yello 和Color::yellow这两种形式都是合法的

5 . c++11中匿名的强类型枚举
     疑问:若在程序中,声明了一个匿名的强枚举类型,应该怎么去使用?

示例5:

#include<iostream>
using namespace std;
enum class{red,yellow,green,black,white} color;
int main(int argc,char **argv)
{
    color = red;   
    //编译失败;‘red’ was not declared in this scope
    bool value = (color == color::red); 
    //编译失败; error: ‘color’ is not a class or namespace
    return 0;
}

通过上面的示例5代码可以得知:若声明 了一个匿名的强枚举类型和示例,我们是无法对其示例进行设置值或去进行比较的,因此官方建议:在使用enum class(强枚举类型)的时候,应该总是提供一个名字。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值