< previous page page_211 next page >

Page 211
LISTING 14.3 PREFIX AND POSTFIX OPERATORS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:     // Listing 14.3
 2:     // Returning the dereferenced this pointer
 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:        const Counter& operator++ ();      // prefix
14:        const Counter operator++ (int);    // postfix
15:
16:     private:
17:        int itsVal;
18:     };
19:
20:     Counter::Counter():
21:     itsVal(0)
22:     {}
23:
24:     const Counter& Counter::operator++()
25:     {
26:        ++itsVal;
27:        return *this;
28:     }
29:
30:     const Counter Counter::operator++(int)
31:     {
32:        Counter temp(*this);
33:        ++itsVal;
34:        return temp;
35:     }
36:
37:     int main()
38:     {
39:        Counter i;
40:        cout << The value of i is  << i.GetItsVal() << endl;
41:        i++;
42:        cout << The value of i is  << i.GetItsVal() << endl;
43:        ++i;
44:        cout << The value of i is  << i.GetItsVal() << endl;
45:        Counter a = ++i;
46:        cout << The value of a:  << a.GetItsVal();
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_211 next page >

If you like this book, buy it!