|

To
solve this and similar problems, C++ provides conversion
operators that can be added to your class. This
allows your class to specify how to do implicit
conversions to built-in types. Listing 10.18 illustrates
this. One note, however: Conversion operators do
not specify a return value, even though they do,
in effect, return a converted value.
Listing
10.18. Converting from Counter to unsigned short().
1:
// Listing 10.18
2:
// conversion operator
3:
4:
typedef unsigned short USHORT;
5:
#include <iostream.h>
6:
7:
class Counter
8:
{
9:
public:
10:
Counter();
11:
Counter(USHORT val);
12:
~Counter(){}
13:
USHORT GetItsVal()const { return itsVal; }
14:
void SetItsVal(USHORT x) {itsVal = x; }
15:
operator unsigned short();
16:
private:
17:
USHORT itsVal;
18:
19:
};
20:
21:
Counter::Counter():
22:
itsVal(0)
23:
{}
24:
25:
Counter::Counter(USHORT val):
26:
itsVal(val)
27:
{}
28:
29:
Counter::operator unsigned short ()
30:
{
31:
return ( USHORT (itsVal) );
32:
}
33:
34:
int main()
35:
{
36:
Counter ctr(5);
37:
USHORT theShort = ctr;
38:
cout << "theShort: " << theShort <<
endl;
39:
return 0;
40:
OUTPUT:
theShort: 5
ANALYSIS: On line 15, the conversion
operator is declared. Note that it has no return
value. The implementation of this function is on
lines 29-32. Line 31 returns the value of itsVal,
converted to a USHORT.
Now
the compiler knows how to turn USHORTs into Counter
objects and vice versa, and they can be assigned
to one another freely.
|