zoukankan      html  css  js  c++  java
  • 枚举

    枚举 enum 

    枚举 enum 也和int struct 一样,是一种数据类型。

    在使用上enum有些类似struct ,在效果上和#define相同。

    typedef enum Week
    {
        Monday    = 1, 
        Tuesday   = 2, 
        Wednesday = 3, 
        Thursday  = 4, 
        Friday    = 5, 
        Saturday  = 6, 
        Sunday    = 7
    }Weekday1,Weekday2;

    比如上面这个例子,使用typedef定义了一个枚举类型Week,同时还用该类型声明了2个未初始化的变量Weekday1 Weekday2

    这里要注意枚举里的成员,只能是整形,所以即便我们不赋初值,系统也会按照顺序给枚举里的类型自动赋值

    比如:

    typedef enum Week
    {
        Monday = 1, 
        Tuesday   , 
        Wednesday , 
        Thursday  , 
        Friday    , 
        Saturday  , 
        Sunday    
    }Weekday1,Weekday2;

    这段代码的效果和上一个完全相同。

    系统自动为后面的Tuesday 等成员按顺序+1赋了值。

    接下来看一下如何给枚举里的成员赋值

    首先不使用typdef,这里展现了4种赋值方式

    #include <stdio.h>
    
    enum Week
    {
        Monday = 1, 
        Tuesday   , 
        Wednesday , 
        Thursday  , 
        Friday    , 
        Saturday  , 
        Sunday    
    }
    Weekday1 = Monday,Weekday2 = Tuesday,Weekday4;
    
    int main()
    {
        enum Week Weekday3 = Friday;
        int Weekday5 = Saturday;
        Weekday4 = Sunday;
        
        printf("Monday     = %d
    ",Weekday1);
        printf("Tuesday    = %d
    ",Weekday2);
        printf("Friday     = %d
    ",Weekday3);
        printf("Saturday   = %d
    ",Weekday5);
        printf("Sunday     = %d
    ",Weekday4);
    
        return 0;
    }

    输出结果如下:

    接下来使用typedef

    #include <stdio.h>
    
    typedef enum Week  //这个Week可以不写
    {
        Monday = 1, 
        Tuesday   , 
        Wednesday , 
        Thursday  , 
        Friday    , 
        Saturday  , 
        Sunday    
    }Weekday,Zhou;
    
    
    int main()
    {
        enum Week Weekday3 = Friday;
        int Weekday5       = Saturday;
        Weekday Weekday4   = Sunday;
        Zhou Weekday2      = Tuesday; 
    
    //  printf("Monday     = %d
    ",Weekday1);
        printf("Tuesday    = %d
    ",Weekday2);
        printf("Wednesday  = %d
    ",Wednesday);
        printf("Friday     = %d
    ",Weekday3);
        printf("Saturday   = %d
    ",Weekday5);
        printf("Sunday     = %d
    ",Weekday4);
    
        return 0;
    }

    输出结果如下:

    枚举变量(Monday、Tuesday等)只能为右值

    不能使用这种方法将其赋值

    Monday = 18;  //错误的做法

  • 相关阅读:
    System.ServiceModel.CommunicationException: 接收HTTP 响应时错误发生
    "智囊"王沪宁先后辅佐三任总书记 _中国经济网
    xx
    我告诉你哦,最好吃的海南鸡饭不在海南…
    服务密码重置_中国移动通信
    移动服务密码怎么查_服务密码忘记了怎么办_百度经验
    http://www.sohu.com/a/162795109_465329
    首页--易配菜-中国餐饮行业最大的综合解决方案提供商
    浙江方圆工程咨询有限公司
    MySQL中间件方案盘点_搜狐科技_搜狐网
  • 原文地址:https://www.cnblogs.com/qifeng1024/p/12469207.html
Copyright © 2011-2022 走看看