Why is enum class preferred over plain enum?

前端 未结 9 2345
灰色年华
灰色年华 2020-11-22 10:12

I heard a few people recommending to use enum classes in C++ because of their type safety.

But what does that really mean?

9条回答
  •  春和景丽
    2020-11-22 10:37

    The basic advantage of using enum class over normal enums is that you may have same enum variables for 2 different enums and still can resolve them(which has been mentioned as type safe by OP)

    For eg:

    enum class Color1 { red, green, blue };    //this will compile
    enum class Color2 { red, green, blue };
    
    enum Color1 { red, green, blue };    //this will not compile 
    enum Color2 { red, green, blue };
    

    As for the basic enums, compiler will not be able to distinguish whether red is refering to the type Color1 or Color2 as in hte below statement.

    enum Color1 { red, green, blue };   
    enum Color2 { red, green, blue };
    int x = red;    //Compile time error(which red are you refering to??)
    

提交回复
热议问题