Bitwise NOT operator
suggest changeOverloading the bitwise NOT (~) is fairly simple. Scroll down for explanation
Overloading outside of class/struct:
T operator~(T lhs)
{
//Do operation
return lhs;
}
Overloading inside of class/struct:
T operator~() const
{
T t(*this);
//Do operation
return t;
}
Note: operator~ returns by value because it must return a new value, not a reference to a local object (that reference would dangle). Returning const T would still allow int a = ~a + 1, but it would also block moving from the result, so the return type is non-const.
Inside the class/struct, make a temporary, because operator~ must not modify *this. Mark it const.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents