Why is enum class preferred over plain enum?

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

    One thing that hasn't been explicitly mentioned - the scope feature gives you an option to have the same name for an enum and class method. For instance:

    class Test
    {
    public:
       // these call ProcessCommand() internally
       void TakeSnapshot();
       void RestoreSnapshot();
    private:
       enum class Command // wouldn't be possible without 'class'
       {
            TakeSnapshot,
            RestoreSnapshot
       };
       void ProcessCommand(Command cmd); // signal the other thread or whatever
    };
    

提交回复
热议问题