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>The following is the output of the above example:
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;
}
void operator!(X)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.)
void Y::operator!()
Parent topic:
Overloading operators (C++ only)
Related reference