Operator Overloading
C++ has a number of built-in types, including int, real, char, and so forth. Each of these has a number of built-in operators, such as addition (+) and multiplication (*). C++ enables you to add these operators to your own classes as well.
In order to explore operator overloading fully, Listing 14.1 creates a new class, Counter. A Counter object will be used in counting (surprise!) in loops and other applications where a number must be incremented, decremented, or otherwise tracked.
Listing 14.1. The Counter Class
0: // Listing 14.1 1: // The Counter class 2: #include <iostream> 3: 4: class Counter 5: { 6: public: 7: Counter(); 8: ~Counter(){} 9: int GetItsVal()const { return itsVal; } 10: void SetItsVal(int x) {itsVal ... |
Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.