Why is enum class preferred over plain enum?

前端 未结 9 2246
灰色年华
灰色年华 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:39

    Enumerations are used to represent a set of integer values.

    The class keyword after the enum specifies that the enumeration is strongly typed and its enumerators are scoped. This way enum classes prevents accidental misuse of constants.

    For Example:

    enum class Animal{Dog, Cat, Tiger};
    enum class Pets{Dog, Parrot};
    

    Here we can not mix Animal and Pets values.

    Animal a = Dog;       // Error: which DOG?    
    Animal a = Pets::Dog  // Pets::Dog is not an Animal
    

提交回复
热议问题