zoukankan      html  css  js  c++  java
  • C++之枚举类型

    • 用户定义类型之一(除了class)。
    • 成员为一组符号常量(用户指定或默认值)。
      1 //Here  monday==0  and  sunday==6
      2 enum Day { monday, tuesday, wednesday, thursday, friday, saturday, sunday }; 
      3 enum Month { jan=1 , feb=2, mar=3, apr=4, may=5, jun=6, 
      4 jul=7, aug=8, sep=9, oct=10, nov=11, dec=12 }  ; 
    • 可以定义枚举类型的对象 它可以参与表达式运算 也可以被作为参数传递给函数。

    • 可隐式转换为int,反之不然(可强制转换,不过用Bjarne Stroustrup的话说:C++从不禁止程序员做愚蠢的事情^-^)。
      1 Month m = feb; 
      2 m=7; // error: can't assign an  int to a Month 
      3 int n = m; // OK: we  can get  the numeric value of a Month 
      4 Month mm = Month(7); // convert  int to Month (unchecked) 
    • 枚举成员并不在枚举类型的作用域内,因此,最好将enum定义在类内。
      1 class A
      2 {
      3 public:
      4     enum Day { monday, tuesday, wednesday, thursday, friday, saturday, sunday }; 
      5 };
      6 
      7 int nDay = A::tuesday;
    • 枚举类型可用来取代#define(不占用内存,且有作用域限制)
      1 class GamePlayer
      2 {
      3 private:
      4     enum{NumTurns = 5};
      5     int Scores[NumTurns];
      6 };
    • 参考《Programming Principles and Practice Using C++》、《C++Primer》、《Effective C++ 3》
  • 相关阅读:
    MyBatis进阶(一)
    git命令整理
    今天的任务--git练习
    深入浅出JavaScript(一)
    数据结构_树_二叉搜索树
    网络_体系结构
    数据结构_树
    算法_五大经典搜索算法
    SpringMVC入门
    spring 线程异步执行
  • 原文地址:https://www.cnblogs.com/dahai/p/2822944.html
Copyright © 2011-2022 走看看