< previous page page_221 next page >

Page 221
Once again, this will generate a compile error. Although the compiler now knows how to create a Counter out of an int, it does not know how to reverse the process.
The int() Operator
To solve this and similar problems, C++ provides conversion operators that can be added to your class. This enables your class to specify how to do implicit conversions to built-in types. Listing 14.9 illustrates this. One note, however: conversion operators do not specify a return value, even though they do, in effect, return a converted value.
LISTING 14.9 CONVERTING FROMCounterTOint()

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:  // Listing 14.9
 2:  // conversion operator
 3:
 4:  #include <iostream.h>
 5:
 6:  class Counter
 7:  {
 8:  public:
 9:      Counter();
10:      Counter(int val);
11:      ~Counter(){}
12:      int GetItsVal()const { return itsVal; }
13:      void SetItsVal(int x) {itsVal = x; }
14:      operator int();
15: private:
16:      int itsVal;
17:
18: };
19:
20: Counter::Counter():
21: itsVal(0)
22: {}
23:
24: Counter::Counter(int val):
25: itsVal(val)
26: {}
27:
28: Counter::operator int ()
29: {
30:    return ( int (itsVal) );
31: }
32:
33: int main()
34: {
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_221 next page >

If you like this book, buy it!