Reusing enum values in separate enum types

坚强是说给别人听的谎言 提交于 2020-01-12 04:21:05

问题


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, NOTPRESENT, UNPLUGGED };
enum DeviceType { UNKNOWN, PLAYBACK, RECORDING };

int _tmain(int argc, _TCHAR* argv[])
{
    DeviceState deviceState = DeviceState::UNKNOWN;
    DeviceType deviceType = DeviceType::UNKNOWN;
    return 0;
}

This makes sense to me, but not to the C++ compiler- it complains: error C2365: 'UNKNOWN' : redefinition; previous definition was 'enumerator' on line 2 of the above. Is there a correct way of doing this, or am I supposed to always use unique enum values? I can't imagine this is always possible to guarantee if I'm including someone else's code.


回答1:


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;



回答2:


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).



来源:https://stackoverflow.com/questions/10411357/reusing-enum-values-in-separate-enum-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!