标签:
转换操作符(conversion operator) 是一种特殊的类成员函数。它定义将类类型值转变为其它类型值的转换。
1 classSmallInt 2 { 3 public: 4 SmallInt(int i =0): val(i) 5 { 6 if( i <0|| i >255) 7 throw std::out_of_range("Bad SmallInt initializer"); 8 } 9 operatorint()const {return val;} 10 private: 11 std::size_t val; 12 };
1 SmallInt si; 2 double dval; 3 si >= dval;//si converted to int and then convert to double
1 if(si)//si converted to int and then convert to bool
1 int calc(int); 2 SmallInt si; 3 int i = calc(si);//convert si to int and call calc
1 //convert si to int then call operator << on the int value 2 cout << si << endl;
1 int ival; 2 SmallInt si =3.541;//constructor 3 //instruct compiler to cast si to int 4 ival =static_cast<int>(si)+3;
1 SmallInt si; 2 double dval; 3 si >= dval;// si converted to int and then convert to double
1 void calc(SmallInt); 2 short sobj; 3 //sobj promoted from short to int 4 //that int converted to SmallInt through the SmallInt(int) constructor 5 calc(sobj);
标签:
原文地址:http://www.cnblogs.com/codetravel/p/4534547.html