Overloading Unary Operators
The latest version of this topic can be found at Overloading Unary Operators.
The unary operators that can be overloaded are the following:
!
(logical NOT)&
(address-of)~
(one's complement)+
(unary plus)-
(unary negation)++
(increment)--
(decrement)conversion operators
The postfix increment and decrement operators (++
and ––) are treated separately in Increment and Decrement.
Conversion operators are also discussed in a separate topic; see User-Defined Type Conversions.
The following rules are true of all other unary operators. To declare a unary operator function as a nonstatic member, you must declare it in the form:
ret-type operator
op
()
where ret-type
is the return type and op
is one of the operators listed in the preceding table.
To declare a unary operator function as a global function, you must declare it in the form:
ret-type operator
op
(arg
)
where ret-type
and op
are as described for member operator functions and the arg
is an argument of class type on which to operate.
Note
There is no restriction on the return types of the unary operators. For example, it makes sense for logical NOT (!
) to return an integral value, but this is not enforced.