How to use enums in C++

前端 未结 14 688
臣服心动
臣服心动 2020-12-04 04:30

Suppose we have an enum like the following:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};

I want to crea

14条回答
  •  时光说笑
    2020-12-04 05:20

    If we want the strict type safety and scoped enum, using enum class is good in C++11.

    If we had to work in C++98, we can using the advice given by InitializeSahib,San to enable the scoped enum.

    If we also want the strict type safety, the follow code can implement somthing like enum.

    #include 
    class Color
    {
    public:
        static Color RED()
        {
            return Color(0);
        }
        static Color BLUE()
        {
            return Color(1);
        }
        bool operator==(const Color &rhs) const
        {
            return this->value == rhs.value;
        }
        bool operator!=(const Color &rhs) const
        {
            return !(*this == rhs);
        }
    
    private:
        explicit Color(int value_) : value(value_) {}
        int value;
    };
    
    int main()
    {
        Color color = Color::RED();
        if (color == Color::RED())
        {
            std::cout << "red" << std::endl;
        }
        return 0;
    }
    

    The code is modified from the class Month example in book Effective C++ 3rd: Item 18

提交回复
热议问题