conversion constructor和cast operator function试用
试用构造函数转换(隐式)和转换操作符
1 #include<iostream> 2 using namespace std; 3 4 class A{ 5 public: 6 A(){};//一定要有花括号表示这是个定义而不只是个声明,否则当object需要调用到这个constructor时会报错error:ld returned 1 exit status 7 A(int a):value(a){ 8 //empty 9 } 10 operator int()const{ 11 return value; 12 } 13 void set(int a){ 14 value=a; 15 } 16 int get(){ 17 return value; 18 } 19 private: 20 int value; 21 }; 22 23 class B{ 24 public: 25 B(){}; 26 B(double b):data(b){ 27 //empty 28 } 29 30 B(A aTest):data(aTest.get()){ 31 //empty 32 } 33 void set(double a){ 34 data=a; 35 } 36 operator double()const{ 37 return data; 38 } 39 operator A()const{ 40 A temp(data); 41 return temp; 42 } 43 private: 44 double data; 45 }; 46 47 void printInt(int val){ 48 cout<<val<<endl; 49 } 50 51 void printDou(double dat){ 52 cout<<dat<<endl; 53 } 54 55 void printA(const A &a){ 56 printInt(a); 57 } 58 59 void printB(const B &b){ 60 printDou(b); 61 } 62 63 int main(){ 64 A aTest; 65 B bTest; 66 67 aTest.set(1); 68 bTest.set(3.15); 69 70 //class->fundamentle 71 printInt(aTest); 72 printDou(bTest); 73 74 cout<<endl; 75 76 int v=3; 77 double d=4.12; 78 79 //fundamental->class 80 printA(v); 81 printB(d); 82 cout<<endl; 83 84 //class->class 85 printA(bTest);//by cast operator function 86 printB(aTest);//by constructor 87 cout<<endl; 88 89 //explicit call to conversion
printA(static_cast<A>(bTest));//这一句会报错,因为编译器既可以选择constructor(隐式),也可以选择operator function,两者都不是完全匹配,都需要编译器再加一步标准转换
//编译器无法选择哪个更好,有二义性,所以error:call of overloaded'A(B&)'is ambiguous
//疑问:为什么在B的 B(A aTest)这个constructor前加一个explicit依然报错ambiguous? 90 printA(bTest.operator A() ); 91 printB(B(aTest)); 92 }
Look, if you had one shot , one opportunity , to seize everything you ever wanted , in one moment.
Would you captrue it , or just let it slip ?

浙公网安备 33010602011771号