【发布时间】:2017-02-16 19:02:00
【问题描述】:
是否可以为枚举定义运算符波浪号~?例如,我的示例中有枚举状态,我希望能够编写 result &= ~STATE_FAIL;。
我做了这样的事情:
#include <iostream>
enum State
{
STATE_OK = 0x0,
STATE_FAIL = 0x1,
STATE_LOW = 0x2,
STATE_HIGH = 0x4
};
State & operator|=(State & a, const State b)
{
a = static_cast<State>(static_cast<int>(a) | static_cast<int>(b));
return a;
}
State & operator&=(State & a, const State b)
{
a = static_cast<State>(static_cast<int>(a) & static_cast<int>(b));
return a;
}
State & operator~(State& a)
{
a = static_cast<State>( ~static_cast<int>(a));
return a;
}
int main()
{
State result = STATE_OK;
result |= STATE_FAIL; // ok
result &= STATE_FAIL; // ok
result &= ~STATE_FAIL; // fail
return 0;
}
我收到以下错误:
在函数
int main():第 35 行:错误:无效转换int到State编译由于 -Wfatal-errors 而终止。
【问题讨论】:
-
枚举的转换在另一个问题中,但它没有显示按值获取参数并返回值而不是@tuple_cat 的答案中的引用对于这个问题。这在创建正确的 bitwise NOT
operator~时很重要。
标签: c++ c++11 visual-c++ enums c++14