Overloading 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~()
{
T t(*this);
//Do operation
return t;
}
Note: operator~
returns by value, because it has to return a new value (the modified value), and not a reference to the value (it would be a reference to the temporary object, which would have garbage value in it as soon as the operator is done). Not const
either because the calling code should be able to modify it afterwards (i.e. int a = ~a + 1;
should be possible).
Inside the class
/struct
you have to make a temporary object, because you can't modify this
, as it would modify the original object, which shouldn't be the case.