美文网首页
c++11系列:enumeration

c++11系列:enumeration

作者: 再见小浣熊 | 来源:发表于2017-05-31 17:39 被阅读0次

枚举类型

从C++11开始,存在了两种枚举类型Unscoped enumerationScoped enumeration

Unscoped enumeration是C++98风格的枚举,也是平时使用的最多的,enum Direction { East, South, West, North }

Scoped enumeration是C++11引入的新的枚举类型,也是更推荐使用的枚举。完整的定义如下enum struct|class name : type { enumerator = constexpr , enumerator = constexpr , ... }
定义的方式和Unscoped enumeration大体一致,只有两个部分有些差异:

  1. struct | class: 只要使用了struct或者class关键字,就表示定义了Scoped enumeration,而这两个关键字本身是等价的,随便使用哪个都没有区别,根据惯例的话更偏向使用class

  2. type:其实C++11以后,两种类型的枚举都可以指定type。这个类型是可以缺省的,这样默认使用的就是int类型。如果不符合自己的使用场景,也可以自己指定类型,但该类型属于integral type,如charintuint8_t等。

Scoped enums的优势

  1. 减少命名空间的污染
    在包含Unscoped enum的作用域内,定义的任何变量不可以和枚举符重名
    enum Color {
        red, green, blue
    };

    enum class Animal {
        cat, dog, fish
    };

    auto red = "red"; // error! redefinition of 'red' as different kind of symbo
    auto cat = "cat"; // OK
  1. 强类型
    Unscoped enum可以隐式地转化为整型,意味着枚举符可以当作整型,甚至float来使用,在某些情况下会引起难以察觉的bug,这也是C++11的期望解决的
    enum Color {
        red, green, blue
    };

    enum class Animal {
        cat, dog, fish
    };

    int a = red; // OK
    int b = Animal::cat; // Error, cannot initialize a variable of type 'int' with an rvalue of type 'Animal'
    Animal c = Animal::cat; // OK
    
    // 当然,如果你非要转化成int也是可以的,虽然不推荐这样做
    // 如果遇到这样的情况,更推荐使用Unscoped enum
    int d = static_cast<int>(Animal::cat); 

参考资料

相关文章

  • c++11系列:enumeration

    枚举类型 从C++11开始,存在了两种枚举类型Unscoped enumeration和Scoped enumer...

  • Enumerations

    Enumeration Syntax The name of enumeration starts with a ...

  • Enumeration与Iterator介绍

    Enumeration Enumeration简介 Enumeration(列举),本身是一个接口,不是一个类。E...

  • Swift Enumeration(斯威夫特枚举)

    Swift Enumeration(斯威夫特枚举) 目录:1、Enumeration Syntax(枚举语法)2、...

  • C++11/14要点梳理

    并行处理 std::future是一个重要的C++11特性。C++11 并发指南系列值得一看。 参考资料 [1] ...

  • Enumeration

    区别于C,swift中的枚举更加灵活。不需要为每个枚举设定值,如果为枚举设定值得话(raw),可以是字符串、字符、...

  • Enumeration

    1.背景介绍 枚举是一个比较重要的知识点,在之前做任务的时候简单的接触了一下,所以这次给大家介绍一下,抛砖引玉。 ...

  • java复习

    Iterator和Enumeration的区别 我们通常用Iterator(迭代器)或者Enumeration(枚...

  • C++11 并发指南

    C++11 并发指南系列[https://www.cnblogs.com/haippy/p/3284540.htm...

  • Enumeration接口

    在学习properties类的过程使用到Enumeration接口,因此学习记录下。 Enumeration接口中...

网友评论

      本文标题:c++11系列:enumeration

      本文链接:https://www.haomeiwen.com/subject/dwyjfxtx.html