Working with Advanced Functions 315
10
Overloading the Addition Operator (operator+)
Overloading the +operator would make for a more natural use of the Counterclass.
Remember, you saw earlier that to overload an operator, you use the structure:
returnTypeoperator op ()
Listing 10.14 illustrates using this to overload the addition operator.
LISTING10.14 operator+
1: // Listing 10.14 - Overload operator plus (+)
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; }
15: Counter operator+ (const Counter &);
16: private:
17: int itsVal;
18: };
19:
20: Counter::Counter(int initialValue):
21: itsVal(initialValue)
22: {}
23:
24: Counter::Counter():
25: itsVal(0)
26: {}
27:
28: Counter Counter::operator+ (const Counter & rhs)
29: {
30: return Counter(itsVal + rhs.GetItsVal());
31: }
32:
33: int main()
34: {
35: Counter varOne(2), varTwo(4), varThree;
36: varThree = varOne + varTwo;
37: cout << “varOne: “ << varOne.GetItsVal()<< endl;
38: cout << “varTwo: “ << varTwo.GetItsVal() << endl;
39: cout << “varThree: “ << varThree.GetItsVal() << endl;
40:
41: return 0;
42: }