Accessing to enum values by '::' in C++

后端 未结 3 1058
逝去的感伤
逝去的感伤 2021-02-13 09:37

I have class like following:

class Car  
{  
public:  
    Car();  
    // Some functions and members and enums  
    enum Color
    {
              


        
相关标签:
3条回答
  • 2021-02-13 10:07

    In current C++ (i.e. C++11 and beyond), you can already access enum values like that:

    enum Color { Red };
    Color c = Color::Red;
    Color d = Red;
    

    You can go further and enforce the use of this notation:

    enum class Color { Red };
    Color c = Color::Red;
    // Color d = Red;   <--  error now
    

    And on a sidenote, you now define the underlying type, which was previously only possible with hacky code (FORCEDWORD or so anyone?):

    enum class Color : char { Red };
    
    0 讨论(0)
  • Name the enum inside the nested class (as example one):

    class Car
    {
    public:
        struct Color
        {
            enum Type
            {
                Red,
                Blue,
                Black
            };
        };
    
        Color::Type getColor();
        void setColor(Color::Type);
    };
    
    0 讨论(0)
  • 2021-02-13 10:18

    When I want to do something like this I tend to use a namespace and a typedef outside of th namespace (though usually I'm doing this globally rather than inside a class). Something like this:

    namespace colors 
    {
        enum Color 
        {
            Red,
            Blue
            ...
        }
    }
    typedef colors::Color Color;
    

    This way you use the namespace to get at the actual colors, but the Color type itself is still globally accessible:

    Color myFav = colors::Red;
    
    0 讨论(0)
提交回复
热议问题