Why is enum class preferred over plain enum?

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

    C++11 FAQ mentions below points:

    conventional enums implicitly convert to int, causing errors when someone does not want an enumeration to act as an integer.

    enum color
    {
        Red,
        Green,
        Yellow
    };
    
    enum class NewColor
    {
        Red_1,
        Green_1,
        Yellow_1
    };
    
    int main()
    {
        //! Implicit conversion is possible
        int i = Red;
    
        //! Need enum class name followed by access specifier. Ex: NewColor::Red_1
        int j = Red_1; // error C2065: 'Red_1': undeclared identifier
    
        //! Implicit converison is not possible. Solution Ex: int k = (int)NewColor::Red_1;
        int k = NewColor::Red_1; // error C2440: 'initializing': cannot convert from 'NewColor' to 'int'
    
        return 0;
    }
    

    conventional enums export their enumerators to the surrounding scope, causing name clashes.

    // Header.h
    
    enum vehicle
    {
        Car,
        Bus,
        Bike,
        Autorickshow
    };
    
    enum FourWheeler
    {
        Car,        // error C2365: 'Car': redefinition; previous definition was 'enumerator'
        SmallBus
    };
    
    enum class Editor
    {
        vim,
        eclipes,
        VisualStudio
    };
    
    enum class CppEditor
    {
        eclipes,       // No error of redefinitions
        VisualStudio,  // No error of redefinitions
        QtCreator
    };
    

    The underlying type of an enum cannot be specified, causing confusion, compatibility problems, and makes forward declaration impossible.

    // Header1.h
    #include 
    
    using namespace std;
    
    enum class Port : unsigned char; // Forward declare
    
    class MyClass
    {
    public:
        void PrintPort(enum class Port p);
    };
    
    void MyClass::PrintPort(enum class Port p)
    {
        cout << (int)p << endl;
    }
    

    .

    // Header.h
    enum class Port : unsigned char // Declare enum type explicitly
    {
        PORT_1 = 0x01,
        PORT_2 = 0x02,
        PORT_3 = 0x04
    };
    

    .

    // Source.cpp
    #include "Header1.h"
    #include "Header.h"
    
    using namespace std;
    int main()
    {
        MyClass m;
        m.PrintPort(Port::PORT_1);
    
        return 0;
    }
    

提交回复
热议问题