You overload a unary operator with either a nonstatic member function that has no parameters, or a nonmember function that has one parameter. Suppose a unary operator @ is called with the statement @t, where t is an object of type T. A nonstatic member function that overloads this operator would have the following form:
return_type operator@()
A nonmember function that overloads the same operator would have the following form:
return_type operator@(T)
An overloaded unary operator may return any type.
The following example overloads the ! operator:
#include <iostream>
using namespace std;
struct X { };
void operator!(X) {
cout << "void operator!(X)" << endl;
}
struct Y {
void operator!() {
cout << "void Y::operator!()" << endl;
}
};
struct Z { };
int main() {
X ox; Y oy; Z oz;
!ox;
!oy;
// !oz;
}
The following is the output of the above example:
void operator!(X)
void Y::operator!()
The operator function call !ox is
interpreted as operator!(X). The call !oy is
interpreted as Y::operator!().(The compiler would not allow !oz because the ! operator has not been defined for class Z.)
Related information