| < Day Day Up > |
|
There are two forms of increment and decrement operator: the postfix form and the prefix form. The function signature of each form changes depending on whether you declare it as a member or non-member function. Example 14.22 gives a Foo class with both increment and decrement operators overloaded as member functions in both postfix and prefix form.
Listing 14.22: foo.h
1 #ifndef _FOO_H 2 #define _FOO_H 3 4 class Foo{ 5 public: 6 Foo(int ival = 0); 7 ~Foo(); 8 int getI(); 9 Foo& operator=(int _i); 10 Foo& operator++(); //prefix increment 11 Foo& operator++(int); //postfix increment 12 Foo& operator--(); //prefix decrement 13 Foo& operator--(int); //postfix decrement 14 friend int operator+(Foo& lhs, Foo& rhs); 15 friend int operator-(Foo& lhs, Foo& rhs); 16 private: 17 int i; 18 }; 19 #endif
The difference between the prefix and postfix form of each operator lies in the number of parameters each takes. The prefix form takes no parameters while the postfix form takes one parameter, which is a dummy integer placeholder so the compiler can distinguish between the prefix and postfix form.
Example 14.23 gives the source code for the foo.cpp file containing the implementation of these operators.
Listing 14.23: foo.cpp
1 #include "foo.h" 2 3 Foo::Foo(int ival):i(ival){} 4 5 Foo::~Foo(){}; 6 7 int Foo::getI(){return i;} 8 9 Foo& Foo::operator=(int _i){ 10 i = _i; 11 return *this; 12 } 13 14 Foo& Foo::operator++(){ 15 ++i; 16 return *this; 17 } 18 19 Foo& Foo::operator++(int){ 20 i++; 21 return *this; 22 } 23 24 Foo& Foo::operator--(){ 25 --i; 26 return *this; 27 } 28 29 Foo& Foo::operator--(int){ 30 i--; 31 return *this; 32 } 33 34 /**** Friend +, - functions *****/ 35 int operator+(Foo& lhs, Foo& rhs){ 36 return lhs.i + rhs.i; 37 } 38 39 int operator-(Foo& lhs, Foo& rhs){ 40 return lhs.i - rhs.i; 41 }
Example 14.24 shows a main() function putting all four operators to use, including two overloaded arithmetic operators.
Listing 14.24: main.cpp
1 #include <iostream> 2 using namespace std; 3 #include "foo.h" 4 5 int main(){ 6 Foo f1(1), f2(2), f3(3); 7 8 cout<<f1.getI()<<", "; 9 cout<<f2.getI()<<", "; 10 cout<<f3.getI()<<endl; 11 12 f1 = f2 + f3; 13 f2 = f1 + f3; 14 f3 = f2++ + f1++; 15 16 cout<<f1.getI()<<", "; 17 cout<<f2.getI()<<", "; 18 cout<<f3.getI()<<endl; 19 20 f1 = f1 - f1; 21 22 cout<<f1.getI()<<endl; 23 24 for(int i=0; i<5; i++){ 25 cout<<f1.getI()<<", "; 26 f1++; 27 } 28 cout<<endl; 29 30 for(int i=0; i<5; i++){ 31 cout<<f1.getI()<<","; 32 ++f1; 33 } 34 cout<<endl; 35 36 for(int i=0; i<5; i++){ 37 cout<<f1.getI()<<", "; 38 --f1; 39 } 40 41 return 0; 42 }
Figure 14-10 shows the results of running example 14.24.
Figure 14-10: Results of Running Example 14.24
| < Day Day Up > |
|