1, conversion operators: A special class member function. When the operator is defined, the compiler will call it automatically where the built-in transformations can be used :
classsmallint{ Public: SmallInt (inti =0): M_val (i) {if(I <0|| i >255) ThrowStd::out_of_range ("Bad SmallInt initializer"); } //The conversion function must be a member function, usually defined as a const operator int()Const{returnM_val;}Private: std::size_t m_val;};intMain () {SmallInt Si ( A); DoubleDval =4.5; //si converted to int, then converted to double if(Si >=dval) {} //si converted to int, then converted to bool if(SI) {} cout<< si << Endl;//si converted to int//3.541 is converted to int first, and then the smallint object is constructed with intSmallInt Si2 =3.541; intIval = static_cast<int> (SI2) +3;//an explicit conversion return 0;}
In addition, the language allows only one-time (Automatic) class-type conversions . That is, (only) through the conversion operator, if the C type can be converted to type B, the B type can be converted to type A, then the C type cannot be converted directly to type A.
Resources:
"C + + Primer"
Continue to learn in ...
C + + Operators