|
|
|
|
|
|
|
In order to create varThree without having to initialize a value for it, a default constructor is required. The default constructor initializes itsVal to 0, as shown on lines 2527. Because varOne and varTwo need to be initialized to a non-zero value, another constructor is created, as shown on lines 2123. Another solution to this problem is to provide the default value 0 to the constructor declared on line 11. |
|
|
|
|
|
|
|
|
The Add() function itself is shown on lines 2932. It works, but its use is unnatural. Overloading the operator + is a more natural use of the Counter class. Listing 14.5 illustrates this. |
|
|
|
 |
|
|
|
|
1: // Listing 14.5
2: //Overload operator plus (+)
3:
4: #include <iostream.h>
5:
6: class Counter
7: {
8: public:
9: Counter();
10: Counter(int initialValue);
11: ~Counter(){}
12: int GetItsVal()const { return itsVal; }
13: void SetItsVal(int x) {itsVal = x; }
14: Counter operator+ (const Counter &);
15: private:
16: int itsVal;
17: };
18:
19: Counter::Counter(int initialValue):
20: itsVal(initialValue)
21: {}
22:
23: Counter::Counter():
24: itsVal(0)
25: {}
26:
27: Counter Counter::operator+ (const Counter & rhs)
28: {
29: return Counter(itsVal + rhs.GetItsVal());
30: }
31:
32: int main()
33: {
34: Counter varOne(2), varTwo(4), varThree; |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|