Working with Advanced Functions 313
10
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: 3 and i: 4
The postfix operator is declared on line 15 and implemented on lines 31–36. The
prefix operator is declared on line 14.
The parameter passed into the postfix operator on line 32 (theFlag) serves to signal that
it is the postfix operator, but this value is never used.
Overloading Binary Mathematical Operators ................................................
The increment operator is a unary operator. It operates on only one object. Many of the
mathematical operators are binary operators; they take two objects (one of the current
class, and one of any class). Obviously, overloading operators such as the addition (+),
subtraction (-), multiplication (*), division (/), and modulus (%) operators is going to be
different from overloading the prefix and postfix operators. Consider how you would
implement overloading the +operator for Count.
The goal is to be able to declare two Countervariables and then add them, as in the fol-
lowing example:
Counter varOne, varTwo, varThree;
VarThree = VarOne + VarTwo;
Once again, you could start by writing a function,Add(), which would take a Counteras
its argument, add the values, and then return a Counterwith the result. Listing 10.13
illustrates this approach.
LISTING10.13 The Add()Function
1: // Listing 10.13 - Add function
2:
3: #include <iostream>
4:
5: using namespace std;
6:
7: class Counter
8: {
9: public:
10: Counter();
11: Counter(int initialValue);
12: ~Counter(){}
13: int GetItsVal()const { return itsVal; }
14: void SetItsVal(int x) {itsVal = x; }
OUTPUT
ANALYSIS