Microsoft KB Archive/814455

= BUG: You receive a &quot;C2676&quot; error message when both unary and binary operators are overloaded for the same operator =

Article ID: 814455

Article Last Modified on 1/19/2006

-

APPLIES TO


 * Microsoft Visual C++ .NET 2003 Standard Edition

-



SYMPTOMS
When both the unary and binary operators for an operator are overloaded for a class, and the binary operator is defined as a non-member operator with the friend specifier in the class scope, you receive the following error message:

error C2676: binary '-' : 'Test' does not define this operator or a conversion to a type acceptable to the predefined operator

The behavior is observed for any operator that can be overloaded both as a unary and binary operator. This includes the minus (-), the plus (+), and the &quot;*&quot; operator.



CAUSE
The compiler picks up the wrong overloaded operator method.



STATUS
Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.



WORKAROUND
To resolve the problem, move the definition of the binary non-member operator outside the class scope. The following code specifies the class that is named Test that overloads the &quot;-=&quot; and the unary minus (-) operator as member operators. The binary minus (-) operator is specified as the non-member operator. The definition of the binary minus (-) operator has been moved outside the class scope. class Test {   friend Test operator-(const Test &a, const Test &b);

Test& operator-=(const Test& m)   { *this = *this - m;       return *this; }

//The code provided below is only for illustration purpose. Test operator-(void) const {       Test dummy; return dummy; } };

//Definition of the overloaded operator is moved out of the class scope for Test. Test operator-(const Test &a, const Test &b) {   Test dummy; return dummy; }



Steps to Reproduce the Behavior
  In Notepad, or any other text editor, paste the following code:
 * 1) include 
 * 2) include 

class Test {   friend Test operator-(const Test &a, const Test &b) {       Test dummy; return dummy; }

Test& operator-=(const Test& m)   { *this = *this - m; //C2676 on this line. return *this; }

Test operator-(void) const {       Test dummy; return dummy; } };

int _tmain(int argc, _TCHAR* argv[]) {   return 0; } Note Both the unary and binary minus(-) operators are defined in the scope of the class, where the operators are being overloaded.  Save the file as Test.cpp .  Open a .NET command prompt, and then type the following command: cl /c Test.cpp 

You receive the compiler error message that is described in the &quot;Symptoms&quot; section of this article.

Keywords: kberrmsg kbbug kbcompiler KB814455

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.