Condividi tramite


Convert-From Operators

Convert-from operators create an object of the class in which the operator is defined from an object of some other class.

Standard C++ does not support convert-from operators; standard C++ uses constructors for this purpose. However, when using CLR types, Visual C++ provide syntactic support for calling convert-from operators.

To interoperate well with other CLS-compliant languages, you may wish to wrap each user-defined unary constructor for a given class with a corresponding convert-from operator.

Remarks

Convert-from operators:

  • Shall be defined as static functions.

  • Can either be implicit (for conversions that do not lose precision such as short-to-int) or explicit, when there may be a loss of precision.

  • Shall return an object of the containing class.

  • Shall have the "from" type as the sole parameter type.

Example

The following sample shows an implicit and explicit "convert-from", user-defined conversion (UDC) operator.

// clr_udc_convert_from.cpp
// compile with: /clr
value struct MyDouble {
   double d;

   MyDouble(int i) {
      d = static_cast<double>(i);
      System::Console::WriteLine("in constructor");
   }

   // Wrap the constructor with a convert-from operator.
   // implicit UDC because conversion cannot lose precision
   static operator MyDouble (int i) {
      System::Console::WriteLine("in operator");
      // call the constructor
      MyDouble d(i);
      return d;
   }

   // an explicit user-defined conversion operator
   static explicit operator signed short int (MyDouble) {
      return 1;
   }
};

int main() {
   int i = 10;
   MyDouble md = i;
   System::Console::WriteLine(md.d);
 
   // using explicit user-defined conversion operator requires a cast  
   unsigned short int j = static_cast<unsigned short int>(md);
   System::Console::WriteLine(j);
}
in operator
in constructor
10
1

See Also

Reference

User-Defined Conversions