zoukankan      html  css  js  c++  java
  • C++ 作用域内枚举

    ——传统的枚举存在一些问题,其中之一是两个枚举类型定义中的枚举量可能发生冲突。

    enum egg {Small, Medium, Large, Jumbo};
    enum t_shirt {Small, Medium, Large, Xlarge};
    

      这将无法通过编译(egg Small和t_shirt Small发生冲突)

    解决办法(新枚举):

    C++11提供了一种新枚举,其枚举量的作用域为类:

    enum class egg {Small, Medium, Large, Jumbo};
    eum class t_shirt {Small, Medium, Large, Xlarge};
    
    • 可使用关键字struct代替class
    • 使用时需使用枚举名来限定枚举量:
      egg choice = egg::Large;    // the Large enumerator of the egg enum
      t_shirt Floyd = t_shirt::Large;    // the Large enumerator of the t_shirt enum
      
    • C++11提高了作用域内枚举的类型安全:
      • 有时,常规枚举将自动转换为整型,如将其赋给int变量或用于比较表达式时,但作用域内枚举不能隐式地转换为整型:
        enum egg_old {Small, Medium, Large, Jumbo};    // unscoped
        enum class t_shirt {Small, Medium, Large, Xlarge};    // scoped
        egg_old one = Medium;    // unscoped
        t_shirt rolf = t_shirt::Large;    // scoped
        int king = one;    // implicit type conversion ofr unscoped
        int ring = rolf;    // not allowed, no implicit type conversion
        if (king < Jumbo)    // allowed
            std::cout<<"Jumbo converted to int before comparison.
        ";
        if (king < t_shirt::Medium)    // not allowed
            std::cout<<"Not allowed: < not defined for scoped enum.
        ";
        

          但在必要时,可显示类型转换:

        int Frodo = int(t_shirt::Small);    // Frodo set to 0
        

          

  • 相关阅读:
    重复点击的解决方案
    判断window.open的页面是否已经被关
    npm run dev 报错 版本太低
    :after 写三角形 border
    input text 在苹果微信浏览器中有上上阴影
    input实时监听
    pre强制 自动换行
    解决iphone safari上的圆角问题
    ACM: 强化训练-Roads in the North-BFS-树的直径裸题
    ACM: 强化训练-Inversion Sequence-线段树 or STL·vector
  • 原文地址:https://www.cnblogs.com/suui90/p/13039563.html
Copyright © 2011-2022 走看看