14: void SetItsVal(int x) {itsVal = x; }
15: void Increment() { ++itsVal; }
16: Counter operator++ ();
17:
18: private:
19: int itsVal;
20: };
21:
22: Counter::Counter():
23: itsVal(0)
24: {}
25:
26: Counter::Counter(int val):
27: itsVal(val)
28: {}
29:
30: Counter Counter::operator++()
31: {
32: ++itsVal;
33: return Counter (itsVal);
34: }
35:
36: int main()
37: {
38: Counter i;
39: cout << “The value of i is “ << i.GetItsVal() << endl;
40: i.Increment();
41: cout << “The value of i is “ << i.GetItsVal() << endl;
42: ++i;
43: cout << “The value of i is “ << i.GetItsVal() << endl;
44: Counter a = ++i;
45: cout << “The value of a: “ << a.GetItsVal();
46: cout << “ and i: “ << i.GetItsVal() << endl;
47: return 0;
48: }
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
On line 11, a new constructor is declared that takes an int. The implementation
is on lines 26–28. It initializes itsValwith the passed-in value.
The implementation of operator++is now simplified. On line 32,itsValis incre-
mented. Then on line 33, a temporary Counterobject is created, initialized to the value
in itsVal, and then returned as the result of the operator++.
OUTPUT
308 Day 10
LISTING10.10 continued
ANALYSIS