美文网首页
[cpp deep dive] enum枚举类型

[cpp deep dive] enum枚举类型

作者: Quasars | 来源:发表于2016-04-30 16:12 被阅读311次
    1. 如何声明一个枚举类型?
      enum color{red, blue, green, orange};//statement with a name of enum type
      enum {red, blue, green, orange};//or without a name
    
    1. 如何合法使用枚举类型?
    color cc1 = red;//valid
    color cc01 = (color)0;//valid
    int crs = red;//valid 'enum' to' int'
    int crr = red + blue;//valid, enum will be converted to int and then calc.
    
    1. 不合法的例子?
    color cc2 = 0;//not valid ,'int' to 'enum'
    color cc3 = 0;cc3++;//not valid, operator‘++’
    color cc4 = red + blue;//not valid, 'int' to 'enum'
    color cc5 = (color)(red + blue);//but this it valid.
    
    color cc6 = (color)127;//undefined behavior but won't get an error. code will work.
    
    1. enum的值 ?
        enum bigstep{first, sec=100, third};//first 's value = 0, sec = 100, third = 101.
        enum bigstep2{aar, aar2 = 0, aar3, aar32 = 1};//multiple enum's type have the same value.
    
    1. enum的sizeof?
        enum size{x1,x2,x3};//sizeof(size) == 4
        enum size2{x11,x22=100000000000000LL,x33};//sizeof(size2) == 8(long long)
    

    上代码片

    #include <stdio.h>
    
    void test_enum(){
    #define PR(c) printf("id: %d\n", (c))
        enum color{r, g, b};
    
        enum bigstep{first, sec=100, third};//first 's value = 0, sec = 100, third = 101.
        enum bigstep2{aar, aar2 = 0, aar3, aar32 = 1};//multiple enum's type have the same value.
        enum {skip01, skip02};
    
        
        color c1,c2,c3;
    //  c1 = 0;//error: invalid conversion from "int" to "test_enum()::color"
    //  c1 = color.r;//error: expected primary-expression before "." token
    //  c1 = color::r;error: ¡®color¡¯ is not a class or namespace
    
    /*  
        OK: enum ==> int
        Not OK: int ==> enum
     */
        c1 = r;//ok
        c1 = (color)0;//ok 
        PR(c1);
        c1 = (color)5;  //undefined behavior
        PR(c1);         //just print value 5.
        c1 = (color)127;//same as above.
        PR(c1); 
        
        c2 = r;
    //  c2++;// error: no ¡®operator++(int)¡¯ declared for postfix ¡®++¡¯ 
        PR(c1+c2);//valid
        int x = c1+c2;//valid
        PR(x);
    //  c3 = r+b;//error: invalid conversion from ¡®int¡¯ to ¡®test_enum()::color
    //  c3 = (color)r+b;//same as above due to order of compute. 
        c3 = (color)(r+b);//valid
    //enum size{a,b,c};
    //enum size2{a,b=1000LL,c};//error: redeclaration of ¡®b¡¯
        enum size{x1,x2,x3};
        enum size2{x11,x22=100000000000000LL,x33};
    
        PR(sizeof(size));
        PR(sizeof(size2));
    
    
    }
    
    int main(){
        test_enum();
        return 0;
    }
    

    6.实际例子?

    further reading:
    <a href=http://www.cnblogs.com/hicjiajia/archive/2009/09/27/1574957.html>c++枚举类型_博客园</a>

    相关文章

      网友评论

          本文标题:[cpp deep dive] enum枚举类型

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