Overloading Compound Assignment Operators: , -, , etc.

 < Day Day Up > 



Overloading Compound Assignment Operators: +=, -=, *=, etc.

The important thing to remember about the compound operators is that they perform both a binary operation and an assignment all in one stroke. This gives a hint regarding their implementation. The Foo class will once again be used to demonstrate the implementation of a compound operator. Example 14.19 gives the declaration of class Foo with the operator+=() declared.

Listing 14.19: foo.h

start example
  1  #ifndef _FOO_H  2  #define _FOO_H  3  4  class Foo{  5   public:  6       Foo(int _i = 0);  7       void setI(int _i);  8       int getI();  9       Foo& operator=(Foo& rhs); 10       Foo& operator+=(Foo& rhs); 11   private: 12       int i; 13  }; 14  #endif
end example

The foo.cpp file is shown in example 14.20.

Listing 14.20: foo.cpp

start example
  1  #include "foo.h"  2  3  Foo::Foo(int _i):i(_i){}  4  5  void Foo::setI(int _i){ i = _i;}  6  7  int Foo::getI(){return i;}  8  9  Foo& Foo::operator=(Foo& rhs){ 10     i = rhs.i; 11     return *this; 12  } 13 14  Foo& Foo::operator+=(Foo& rhs){ 15       i = i+rhs.i; 16       return *this; 17  }
end example

The operator+=() definition begins on line 14 with the real work happening on line 15. The function ends by returning a reference to the current object. Example 14.21 gives a main() function showing the compound operator in action.

Listing 14.21: main.cpp

start example
  1  #include <iostream>  2  using namespace std;    3  #include "foo.h"  4  5  int main(){  6  7       Foo f1(3), f2(4);  8  9       f1+=f2; 10        cout<<f1.getI()<<endl; 11       return 0; 12  }
end example

Figure 14-9 shows the results of running 14.21.


Figure 14-9: Results of Running Example 14.21



 < Day Day Up > 



C++ for Artists. The Art, Philosophy, and Science of Object-Oriented Programming
C++ For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504028
EAN: 2147483647
Year: 2003
Pages: 340
Authors: Rick Miller

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