[英]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;
}
This makes sense to me, but not to the C++ compiler- it complains: error C2365: 'UNKNOWN' : redefinition; previous definition was 'enumerator'
这对我有意义,但对C ++编译器没有意义 - 它抱怨:
error C2365: 'UNKNOWN' : redefinition; previous definition was 'enumerator'
error C2365: 'UNKNOWN' : redefinition; previous definition was 'enumerator'
on line 2 of the above. error C2365: 'UNKNOWN' : redefinition; previous definition was 'enumerator'
上面第2行的error C2365: 'UNKNOWN' : redefinition; previous definition was 'enumerator'
。 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.
我无法想象,如果我包含其他人的代码,我总是可以保证。
For those using C++11, you may prefer to use: 对于那些使用C ++ 11的人,您可能更喜欢使用:
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). 请注意,这是强类型的,因此您需要手动将它们强制转换为整数(或其他任何内容)。
You can, and should, include your enums in a namespace
: 您可以而且应该在
namespace
包含您的枚举:
namespace DeviceState
{
enum DeviceState{ UNKNOWN, ACTIVE, DISABLED, NOTPRESENT, UNPLUGGED };
}
namespace DeviceType
{
enum DeviceType{ UNKNOWN, PLAYBACK, RECORDING };
}
//...
DeviceType::DeviceType x = DeviceType::UNKNOWN;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.