|
|
|
|
|
|
|
LISTING 14.1 THECounter CLASS |
|
|
|
 |
|
|
|
|
1: // Listing 14.1
2: // The Counter class
3:
4: typedef unsigned short int;
5: #include <iostream.h>
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:
15: private:
16: int itsVal;
17:
18: };
19:
20: Counter::Counter():
21: itsVal(0)
22: {};
23:
24: int main()
25: {
26: Counter i;
27: cout << The value of i is << i.GetItsVal() << endl;
28: return 0;
29: } |
|
|
|
|
|
|
|
|
Analysis: As it stands, this is a pretty useless class. It is defined on lines 718. Its only member variable is an int. The default constructor, which is declared on line 10 and whose implementation is on line 20, initializes the one member variable, itsVal, to 0. |
|
|
|
|
|
|
|
|
Unlike a real, built-in, honest, red-blooded int, the counter object cannot be incremented, decremented, added, assigned, or otherwise manipulated. In exchange for this, it makes printing its value far more difficult! |
|
|
|
|
|
|
|
|
Writing an Increment Function. |
|
|
|
|
|
|
|
|
Operator overloading restores much of the functionality that has been denied to user-defined classes such as Counter. Listing 14.2 illustrates how to overload the increment operator. |
|
|
|
|
|