Sams Teach Yourself C++ in 21 Days

(singke) #1
LISTING10.18 Converting from Counterto unsigned short()
1: // Listing 10.18 - Conversion Operators
2: #include <iostream>
3:
4: class Counter
5: {
6: public:
7: Counter();
8: Counter(int val);
9: ~Counter(){}
10: int GetItsVal()const { return itsVal; }
11: void SetItsVal(int x) {itsVal = x; }
12: operator unsigned int();
13: private:
14: int itsVal;
15: };
16:
17: Counter::Counter():
18: itsVal(0)
19: {}
20:
21: Counter::Counter(int val):
22: itsVal(val)
23: {}
24:
25: Counter::operator unsigned int ()
26: {
27: return ( int (itsVal) );
28: }
29:
30: int main()
31: {
32: Counter ctr(5);
33: int theInt = ctr;
34: std::cout << “theInt: “ << theInt << std::endl;
35: return 0;
36: }

theShort: 5

On line 12, the conversion operator is declared. Note that this declaration starts
with the operatorkeyword, and that it has no return value. The implementation of
this function is on lines 25–28. Line 27 returns the value of itsVal, converted to an int.
Now, the compiler knows how to turn ints into Counterobjects and vice versa, and they
can be assigned to one another freely. You assign and return other data types in the exact
same manner.

OUTPUT


324 Day 10


ANALYSIS
Free download pdf