Overloading Unary Operators
Go Up to Overloading Operator Functions Overview Index (C++)
You can overload a prefix or postfix unary operator by declaring a nonstatic member function taking no arguments, or by declaring a nonmember function taking one argument. If @ represents a unary operator, @x and x@ can both be interpreted as either x.operator@() or operator@(x), depending on the declarations made. If both forms have been declared, standard argument matching is applied to resolve any ambiguity.
- Under C++ 2.0, an overloaded operator ++ or -- is used for both prefix and postfix uses of the operator.
- With C++ 2.1, when an operator ++ or operator -- is declared as a member function with no parameters, or as a nonmember function with one parameter, it only overloads the prefix operator ++ or operator --. You can only overload a postfix operator ++ or operator -- by defining it as a member function taking an int parameter or as a nonmember function taking one class and one int parameter.
When only the prefix version of an operator ++ or operator -- is overloaded and the operator is applied to a class object as a postfix operator, the compiler issues a warning. Then it calls the prefix operator, allowing 2.0 code to compile. The preceding example results in the following warnings:
Warning: Overloaded prefix 'operator ++' used as a postfix operator in function func() Warning: Overloaded prefix 'operator --' used as a postfix operator in function func()
See Also
- Example Of Overloading Operators
- Overloaded Operators And Inheritance
- Overloading Binary Operators
- Overloading Operator Functions
- Overloading The Assignment operator = (C++)
- Overloading The Class Member Access Operators ->
- Overloading The Function Call Operator ( )
- Overloading The Subscript Operator