12.5 MEMBER-FUNCTION OVERLOAD DEFINITIONS FOR UNARY OPERATORS


12.5 MEMBER-FUNCTION OVERLOAD DEFINITIONS FOR UNARY OPERATORS

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.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net