|
As with binary operators, if the arity of an operator is unary with respect to the built-in types, then such an operator can be overloaded and made to behave like a unary operator for the user-defined types. As before, this overloading may be accomplished either by supplying a global overload definition or a member-function overload definition.
Consider again the case of the MyComplex class, but with just the unary operator ‘-’ defined this time for changing the sign of a complex number, and the previously presented overloaded binary operator ‘<<’ so that we can see the results of applying the unary operator to a MyComplex object:
//OverloadUnaryGlobal.cc #include <iostream> using namespace std; class MyComplex { double re, im; public: MyComplex( double r, double i ) : re(r), im(i) {} double getReal() const { return re; } double getImag() const { return im; } }; // global overload definition for "-" as a unary operator MyComplex operator-( const MyComplex arg ) { return MyComplex( -arg.getReal(), -arg.getImag()); } //global overload definition for "<<" as a binary operator ostream&operator<< ( ostream&os, const MyComplex&arg ) { double d1 = arg.getReal(); double d2 = arg.getImag(); os <<"("<< arg.getReal() << "," << arg.getImag() << "," endl; return os; } int main() { MyComplex c(3, 4); cout << c; // (3, 4) cout << -c; // (-3, -4) return 0; }
The global overload definition shown here for operator-as a unary operator function parallels the global overload definition for operator- shown in Section 12.2 as a binary operator function.
|