是否可以爲運算符定義運算符tilde ~
?例如,我在我的例子中枚舉了State,我希望能夠編寫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;
}
我收到以下錯誤:
In function
int main()
: Line 35: error: invalid conversion fromint
toState
compilation terminated due to -Wfatal-errors.
枚舉的鑄件中的其他問題,但它並不顯示了結通過值的參數和返回值而不是@tuple_cat的答案中的引用對此問題。創建正確的_bitwise NOT_'operator〜'時,這很重要。 –