[英]Overloading the tilde “~” operator for enums
Is it possible to define operators tilde ~
for enums? 是否有可能定义波浪运营商
~
对枚举? For example I have enum State in my example and I would like to be able to write result &= ~STATE_FAIL;
例如,我在示例中有枚举State,并且我希望能够写入
result &= ~STATE_FAIL;
. 。 I did something like this:
我做了这样的事情:
#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;
}
I get the following error: 我收到以下错误:
In function
int main()
: Line 35: error: invalid conversion fromint
toState
compilation terminated due to -Wfatal-errors.在函数
int main()
:第35行:错误:由于-Wfatal-errors,从int
到State
编译的无效转换终止。
The error you're getting is caused by taking the parameter as a non-const reference (which cannot bind to temporaries, which the expression STATE_FAIL
is). 您收到的错误是由于将参数作为非常量引用(无法绑定到
STATE_FAIL
表达式的STATE_FAIL
对象)引起的。
Also there's something wrong in your operator~
implementation: eg your operator~
modifies the parameter which is not the usual conventional behavior of ~
, as shown here . 也有一些错误的
operator~
实现:例如,你的operator~
修改这不是通常的传统行为的参数~
,如图所示这里 。
This should work in the expected way, ie it doesn't modify its argument and only returns the result of the operation: 这应该以预期的方式工作,即,它不会修改其参数,而只会返回操作的结果:
State operator~(const State a)
{
return static_cast<State>(~static_cast<int>(a));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.