在单独的枚举类型中重用枚举值 [英] Reusing enum values in separate enum types
本文介绍了在单独的枚举类型中重用枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在单独的类型中重用相同的枚举值?我希望能够执行以下操作:
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;
}
这对我来说很有意义,但对C ++编译器却不行,它抱怨: 错误C2365:未知:重新定义;先前的定义是上述第2行中的枚举数
。有没有这样做的正确方法,还是应该始终使用唯一的枚举值?我无法想象这总是可以保证是否包含其他人的代码。
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.
推荐答案
您可以并且应该,将您的枚举包含在命名空间
中:
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;
这篇关于在单独的枚举类型中重用枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文