A unary operator for a class can be overloaded as a non-static
member function with no arguments or as a non-member function with one argument that must be an object (or a reference to an object) of the class. Member functions that implement overloaded operators must be non-static
so that they can access the non-static
data in each object of the class.
Consider overloading unary operator !
to test whether an object of your own String
class is empty. Such a function would return a bool
result. When a unary operator such as !
is overloaded as a member function with no arguments and the compiler sees the expression !s
(in which s
is an object of class String
), the compiler generates the function call s.operator!()
. The operand s
is the String
object for which the String
class member function operator!
is being invoked. The function is declared as follows:
class String {
public:
bool operator!() const;
...
};
A unary operator such as !
may be overloaded as a non-member function with one parameter. If s
is a String
class object (or a reference to a String
class object), then !s
is treated as if the call operator!(s)
had been written, invoking the non-member operator!
function that’s declared as follows:
bool operator!(const String&);