This code intends to create a new Counter,a, and then assign to it the value in iafter i
is incremented. The built-in copy constructor will handle the assignment, but the current
increment operator does not return a Counterobject. It returns void. You can’t assign a
void to anything, including a Counterobject. (You can’t make something from nothing!)
Returning Types in Overloaded Operator Functions......................................
Clearly, what you want is to return a Counterobject so that it can be assigned to another
Counterobject. Which object should be returned? One approach is to create a temporary
object and return that. Listing 10.9 illustrates this approach.
LISTING10.9 Returning a Temporary Object
1: // Listing 10.9 - operator++ returns a temporary object
2:
3: #include <iostream>
4:
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: Counter operator++ ();
16:
17: private:
18: int itsVal;
19:
20: };
21:
22: Counter::Counter():
23: itsVal(0)
24: {}
25:
26: Counter Counter::operator++()
27: {
28: ++itsVal;
29: Counter temp;
30: temp.SetItsVal(itsVal);
31: return temp;
32: }
33:
34: int main()
35: {
306 Day 10