Sams Teach Yourself C++ in 21 Days

(singke) #1
12: void SetItsVal(int x) {itsVal = x; }
13: void Increment() { ++itsVal; }
14:
15: private:
16: int itsVal;
17: };
18:
19: Counter::Counter():
20: itsVal(0)
21: {}
22:
23: int main()
24: {
25: Counter i;
26: cout << “The value of i is “ << i.GetItsVal() << endl;
27: i.Increment();
28: cout << “The value of i is “ << i.GetItsVal() << endl;
29: return 0;
30: }

The value of i is 0
The value of i is 1
Listing 10.7 adds an Incrementfunction, defined on line 13. Although this
works, it is cumbersome to use. The program cries out for the capability to add a
++operator, and, of course, this can be done.

Overloading the Prefix Operator ....................................................................


Prefix operators can be overloaded by declaring functions with the form:
returnTypeoperator op ()
Here,opis the operator to overload. Thus, the ++operator can be overloaded with the
following syntax:
void operator++ ()
This statement indicates that you are overloading the ++operator and that it will not
result in a return value—thus voidis the return type. Listing 10.8 demonstrates this alter-
native.

LISTING10.8 Overloadingoperator++
1: // Listing 10.8 - The Counter class
2: // prefix increment operator
3:

OUTPUT


304 Day 10


LISTING10.7 continued

ANALYSIS
Free download pdf