|
Paralleling our discussion for binary operators in Section 12.3, the following example shows a member-function overload definition for ‘-’ as a unary operator.
//OverloadUnaryMemb.cc #include <iostream> using namespace std; class MyComplex { double re, im; public: MyComplex( double r, double i ) : re(r), im(i) {} MyComplex operator-() const; friend ostream&operator<< ( ostream&, MyComplex&); }; //Member-function overload definition for "-""-" MyComplex MyComplex::operator-() const { //(A) return MyComplex( -re, -im ); } //This overload definition has to stay global ostream&operator<< ( ostream&os, const MyComplex&c ) { os << "(" << c.re << "," << c.im << ")" << endl; return os; } int main() { MyComplex c(3, 4); MyComplex z = -c; //(B) cout << z << endl; // (-3, -4) return 0; }
Note that the following statement in line (B) of the program
MyComplex z = -c;
is translated by the compiler into
MyComplex z = c.operator-();
which makes c the invoking object. Thus the values of re and im available inside the definition of the operator- function in line (A) would then correspond to the MyComplex number c.
|