Working with Advanced Functions 305
10
4: #include <iostream>
5: using namespace std;
6:
7: class Counter
8: {
9: public:
10: Counter();
11: ~Counter(){}
12: int GetItsVal()const { return itsVal; }
13: void SetItsVal(int x) {itsVal = x; }
14: void Increment() { ++itsVal; }
15: void operator++ () { ++itsVal; }
16:
17: private:
18: int itsVal;
19: };
20:
21: Counter::Counter():
22: itsVal(0)
23: {}
24:
25: int main()
26: {
27: Counter i;
28: cout << “The value of i is “ << i.GetItsVal() << endl;
29: i.Increment();
30: cout << “The value of i is “ << i.GetItsVal() << endl;
31: ++i;
32: cout << “The value of i is “ << i.GetItsVal() << endl;
33: return 0;
34: }
The value of i is 0
The value of i is 1
The value of i is 2
On line 15,operator++is overloaded. You can see on line 15 that the overloaded
operator simply increments the value of the private member,itsVal. This over-
loaded operator is then used on line 31. This use is much closer to the syntax of a built-in
type such as int.
At this point, you might consider putting in the extra capabilities for which Counterwas
created in the first place, such as detecting when the Counteroverruns its maximum size.
A significant defect exists in the way the increment operator was written, however. If you
want to put the Counteron the right side of an assignment, it will fail. For example,
Counter a = ++i;
OUTPUT
LISTING10.8 continued
ANALYSIS