Reusing enum values in separate enum types

后端 未结 2 1124
礼貌的吻别
礼貌的吻别 2021-02-07 04:58

Is there a way to reuse the same enum value in separate types? I\'d like to be able to something like the following:

enum DeviceState { UNKNOWN, ACTIVE, DISABLED         


        
相关标签:
2条回答
  • 2021-02-07 05:37

    For those using C++11, you may prefer to use:

    enum class Foo
    

    instead of just:

    enum Foo
    

    This provides similar syntax and benefits from as namespaces. In your case, the syntax would be:

    enum class DeviceState { UNKNOWN, ACTIVE, DISABLED, NOTPRESENT, UNPLUGGED };
    DeviceState deviceState = DeviceState::UNKNOWN;
    

    Note that this is strongly typed so you will need to manually cast them to ints (or anything else).

    0 讨论(0)
  • 2021-02-07 05:39

    You can, and should, include your enums in a namespace:

    namespace DeviceState
    {
        enum DeviceState{ UNKNOWN, ACTIVE, DISABLED, NOTPRESENT, UNPLUGGED };
    }
    namespace DeviceType
    {
        enum DeviceType{ UNKNOWN, PLAYBACK, RECORDING };
    }
    
    //...
    
    DeviceType::DeviceType x = DeviceType::UNKNOWN;
    
    0 讨论(0)
提交回复
热议问题