< previous page page_212 next page >

Page 212
LISTING 14.3 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
47:        cout <<  and i:  << i.GetItsVal() << endl;
48:        a = i++;
49:        cout << The value of a:  << a.GetItsVal();
50:        cout <<  and i:  << i.GetItsVal() << endl;
51:        return 0;
52:     }

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
The value of a: 4 and i: 4
Analysis: The postfix operator is declared on line 14 and implemented on lines 3035. Note that the call to the prefix operator on line 13 does not include the flag integer (x), but is used with its normal syntax. The postfix operator uses a flag value (x) to signal that it is the postfix and not the prefix. The flag value (x) is never used, however.
operator+
New Term: The Increment operator is a unary operator, which means that it operates on one object only. The addition operator (+) is a binary operator, where two objects are involved. How do you implement overloading the + operator for Count?
The goal is to be able to declare two Counter variables and then add them, as in this example:
Counter varOne, varTwo, varThree;
VarThree = VarOne + VarTwo;
Once again, you could start by writing a function, Add(), that would take a Counter as its argument, add the values, and then return a Counter with the result. Listing 14.3 illustrates this approach.
LISTING 14.4 THEAdd() FUNCTION

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:     // Listing 14.4
 2:     // Add function
 3:
 4:     #include <iostream.h>
 5:
 6:     class Counter
 7:     {
 8:     public:
 9:       Counter();
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_212 next page >

If you like this book, buy it!