两个枚举之间重载强制转换运算符
有没有办法重载强制转换运算符以在两个枚举之间进行转换?
在我的代码中,
enum devStatus
{
NOT_OPERATING,
INITIALISING,
DEGRADED,
NORMAL
};
enum dataStatus
{
UNAVAILABLE = 1,
DEGRADED,
NORMAL
}
NOT_OPERATING 和 INITIALISING 映射到 UNAVAILABLE; DEGRADED 和 NORMAL 直接映射。这些是通过外部接口修复的。
我正在寻找一种在 devStatus
和 dataStatus
之间进行转换的方法,并且希望能够编写如下内容:
devStatus devSts;
getDeviceStatus(&devSts);
dataStatus dataSts = (dataStatus)devSts;
我知道如果这些是类,我可以编写 devStatus::operator dataStatus()
来执行此操作。有没有办法对枚举执行此操作?
我可以有一个免费的功能 dataStatus devStatus2dataStatus(const devStatus& desSts)
Is there a way to overload a cast operator to convert between two enums?
In my code I have
enum devStatus
{
NOT_OPERATING,
INITIALISING,
DEGRADED,
NORMAL
};
enum dataStatus
{
UNAVAILABLE = 1,
DEGRADED,
NORMAL
}
where NOT_OPERATING and INITIALISING map to UNAVAILABLE; DEGRADED and NORMAL map straight across. These are fixed by external interfaces.
I am looking for a way to convert between devStatus
and dataStatus
and would like to be able to write something like:
devStatus devSts;
getDeviceStatus(&devSts);
dataStatus dataSts = (dataStatus)devSts;
I know that if these were classes, I could write devStatus::operator dataStatus()
to do this. Is there a way of doing this for a enums?
I could just have a free functiondataStatus devStatus2dataStatus(const devStatus& desSts)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 C++ 中,转换运算符只能在类、结构和联合声明中声明。它们不能在类型之外声明(例如,operator+)。枚举类型声明不支持实例成员,因此您需要使用转换函数。这样做也会让调用代码更加清晰。以下示例演示了这一点,使用自定义命名空间来确定枚举和转换函数的范围:
In C++, conversion operators can only be declared within class, struct, and union declarations. They cannot be declared outside the type (like operator+, for example). Enum type declarations do not support instance members, so you will need to go with the conversion function. Doing so will also make the calling code clearer. The following example demonstrates this, using custom namespaces to scope the enumerations and conversion functions: