|

What
happens when you try to assign a variable of a built-in
type, such as int or unsigned short, to an object
of a user-defined class? Listing 10.16 brings back
the Counter class, and attempts to assign a variable
of type USHORT to a Counter object.
WARNING: Listing 10.16 will not compile!
Listing
10.16. Attempting to assign a Counter to a USHORT
1:
// Listing 10.16
2:
// This code won’t compile!
3:
4:
typedef unsigned short USHORT;
5:
#include <iostream.h>
6:
7:
class Counter
8:
{
9:
public:
10:
Counter();
11:
~Counter(){}
12:
USHORT GetItsVal()const { return itsVal; }
13:
void SetItsVal(USHORT x) {itsVal = x; }
14:
private:
15:
USHORT itsVal;
16:
17:
};
18:
19:
Counter::Counter():
20:
itsVal(0)
21:
{}
22:
23:
int main()
24:
{
25:
USHORT theShort = 5;
26:
Counter theCtr = theShort;
27:
cout << "theCtr: " << theCtr.GetItsVal()
<< endl;
28:
return ;0
29:
}
OUTPUT:
Compiler error! Unable to convert USHORT to Counter
ANALYSIS: The Counter class declared
on lines 7-17 has only a default constructor. It
declares no particular method for turning a USHORT
into a Counter object, and so line 26 causes a compile
error. The compiler cannot figure out, unless you
tell it, that, given a USHORT, it should assign
that value to the member variable itsVal.
Listing
10.17 corrects this by creating a conversion operator:
a constructor that takes a USHORT and produces a
Counter object.
Listing
10.17. Converting USHORT to Counter.
1:
// Listing 10.17
2:
// Constructor as 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:
private:
16:
USHORT itsVal;
17:
18:
};
19:
20:
Counter::Counter():
21:
itsVal(0)
22:
{}
23:
24:
Counter::Counter(USHORT val):
25:
itsVal(val)
26:
{}
27:
28:
29:
int main()
30:
{
31:
USHORT theShort = 5;
32:
Counter theCtr = theShort;
33:
cout << "theCtr: " << theCtr.GetItsVal()
<< endl;
34:
return 0;
35:
OUTPUT:
theCtr: 5
ANALYSIS: The important change is on
line 11, where the constructor is overloaded to
take a USHORT, and on lines 24-26, where the constructor
is implemented. The effect of this constructor is
to create a Counter out of a USHORT. Given this,
the compiler is able to call the constructor that
takes a USHORT as its argument. What happens, however,
if you try to reverse the assignment with the following?
1:
Counter theCtr(5);
2:
USHORT theShort = theCtr;
3:
cout << "theShort : " << theShort <<
endl;
Once
again, this will generate a compile error. Although
the compiler now knows how to create a Counter out
of a USHORT, it does not know how to reverse the
process.
|