|
|
|
|
|
|
|
Listing 14.7 will not compile! |
|
|
|
|
|
|
|
|
|
LISTING 14.7 ATTEMPTING TO ASSIGN A COUNTER TO AN INT |
|
|
|
 |
|
|
|
|
1: // Listing 14.7
2: // This code won't compile!
3:
4: #include <iostream.h>
5:
6: class Counter
7: {
8: public:
9: Counter();
10: ~Counter(){}
11: int GetItsVal()const { return itsVal; }
12: void SetItsVal(int x) {itsVal = x; }
13: private:
14: int itsVal;
15:
16: };
17:
18: Counter::Counter():
19: itsVal(0)
20: {}
21:
22: int main()
23: {
24: int theShort = 5;
25: Counter theCtr = theShort;
26: cout << theCtr: << theCtr.GetItsVal() << endl;
27: return 0;
28: } |
|
|
|
|
|
|
|
|
Compiler error! Unable to convert int to Counter |
|
|
|
|
|
|
|
|
Analysis: The Counter class declared on lines 616 has only a default constructor. It declares no particular method for turning an int into a Counter object, so line 25 causes a compile error. The compiler cannot figure out, unless you tell it, that given an int it should assign that value to the member variable itsVal. |
|
|
|
|
|
|
|
|
Listing 14.8 corrects this by creating a conversion operator: a constructor that takes an int and produces a Counter object. |
|
|
|
|
|