Skip to content

Latest commit

 

History

History
94 lines (81 loc) · 2.85 KB

File metadata and controls

94 lines (81 loc) · 2.85 KB
title Overloaded Operators | Microsoft Docs
ms.custom
ms.date 11/04/2016
ms.reviewer
ms.suite
ms.technology
cpp-windows
ms.tgt_pltfrm
ms.topic article
dev_langs
C++
helpviewer_keywords
operator overloading, in a CLR class
operators [C++], overloading
ms.assetid 30391426-afe7-4497-bf22-e4816c1e48c8
caps.latest.revision 9
author mikeblome
ms.author mblome
manager ghogen
translation.priority.ht
cs-cz
de-de
es-es
fr-fr
it-it
ja-jp
ko-kr
pl-pl
pt-br
ru-ru
tr-tr
zh-cn
zh-tw

Overloaded Operators

Operator overloading has changed significantly from Managed Extensions for C++ to Visual C++.

In the declaration of a reference type, for example, rather than using the native operator+ syntax, you explicitly write out the underlying internal name of the operator - in this case, op_Addition. In addition, the invocation of an operator has to be explicitly invoked through that name, thus precluding the two primary benefits of operator overloading: (a) the intuitive syntax, and (b) the ability to intermix new types with existing types. For example:

public __gc __sealed class Vector {  
public:  
   Vector( double x, double y, double z );  
  
   static bool    op_Equality( const Vector*, const Vector* );  
   static Vector* op_Division( const Vector*, double );  
   static Vector* op_Addition( const Vector*, const Vector* );  
   static Vector* op_Subtraction( const Vector*, const Vector* );  
};  
  
int main()  
{  
   Vector *pa = new Vector( 0.231, 2.4745, 0.023 );  
   Vector *pb = new Vector( 1.475, 4.8916, -1.23 );   
  
   Vector *pc1 = Vector::op_Addition( pa, pb );  
   Vector *pc2 = Vector::op_Subtraction( pa, pc1 );  
   Vector *pc3 = Vector::op_Division( pc1, pc2->x );  
  
   if ( Vector::op_Equality( pc1, pc2 ))  
      ;  
}  

In the new syntax, the usual expectations of a native C++ programmer are restored, both in the declaration and use of the static operators. Here is the Vector class translated into the new syntax:

public ref class Vector sealed {  
public:  
   Vector( double x, double y, double z );  
  
   static bool    operator ==( const Vector^, const Vector^ );  
   static Vector^ operator /( const Vector^, double );  
   static Vector^ operator +( const Vector^, const Vector^ );  
   static Vector^ operator -( const Vector^, const Vector^ );  
};  
  
int main()  
{  
   Vector^ pa = gcnew Vector( 0.231, 2.4745, 0.023 );  
   Vector^ pb = gcnew Vector( 1.475,4.8916,-1.23 );  
  
   Vector^ pc1 = pa + pb;  
   Vector^ pc2 = pa - pc1;  
   Vector^ pc3 = pc1 / pc2->x;  
  
   if ( pc1 == pc2 )  
      ;  
}  

See Also

Member Declarations within a Class or Interface (C++/CLI)