Freigeben über


User-Defined Conversions

This section discusses user-defined conversions (UDC) when one of the types in the conversion is a reference or instance of a value type or reference type.

Remarks

A user-defined conversion can either be implicit or explicit. A UDC should be implicit if the conversion does not result in a loss of information. Otherwise an explicit UDC should be defined.

A native class's constructor can be used to convert a reference or value type to a native class.

For more information about conversions, see Implicit Boxing and Standard Conversions.

This section contains the following topics:

Example

// mcpp_User_Defined_Conversions.cpp
// compile with: /clr
#include "stdio.h"
ref class R;
class N;

value class V {
   static operator V(R^) {
      return V();
   }
};

ref class R {
public:
   static operator N(R^);
   static operator V(R^) {
      System::Console::WriteLine("in R::operator N");
      return V();
   }
};

class N {
public:
   N(R^) {
      printf("in N::N\n");
   }
};

R::operator N(R^) {
   System::Console::WriteLine("in R::operator N");
   return N(nullptr);
}

int main() {
   // Direct initialization:
   R ^r2;
   N n2(r2);   // direct initialization, calls constructor
   static_cast<N>(r2);   // also direct initialization

   R ^r3;
   // ambiguous V::operator V(R^) and R::operator V(R^)
   // static_cast<V>(r3);   
}

in N::N
in N::N

See Also

Concepts

Classes and Structs (Managed)