< previous page page_209 next page >

Page 209
LISTING 14.2 OVERLOADING THE INCREMENT OPERATOR

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:    // Listing 14.2
 2:    // Overloading the increment operator
 3:
 4:    #include <iostream.h>
 5:
 6:    class Counter
 7:    {
 8:    public:
 9:      Counter();
10:      ~Counter(){}
11:      int GetItsVal()const { return itsVal; }
12:      void SetItsVal(int x) {itsVal = x; }
13:      void Increment() { ++itsVal; }
14:      const Counter& operator++ ();
15:
16:    private:
17:       int itsVal;
18:
19:    };
20:
21:    Counter::Counter():
22:    itsVal(0)
23:    {};
24:
25:    const Counter& Counter::operator++()
26:    {
27:       ++itsVal;
28:       return *this;
29:    }
30:
31:    int main()
32:    {
33:       Counter i;
34:       cout << The value of i is  << i.GetItsVal() << endl;
35:       i.Increment();
36:       cout << The value of i is  << i.GetItsVal() << endl;
37:       ++i;
38:       cout << The value of i is  << i.GetItsVal() << endl;
39:       Counter a = ++i;
40:       cout << The value of a:  << a.GetItsVal();
41:       cout <<  and i:  << i.GetItsVal() << endl;
42:       return 0;
43:    }

Output:
The value of i is 0
The value of i is 1
The value of i is 2
The value of a: 3 and i: 3

 
< previous page page_209 next page >

If you like this book, buy it!