简体   繁体   中英

Error when implementing overloading operator “+”

I have a MyClass which is a linked list for which I have overidden the operator+:

MyNode
{
   int value;
   MyNode* link;
}
MyClass
{
   MyNode* first;
   MyNode* current;
   MyNode* last;
   int count;
}
MyClass MyClass::operator+(MyClass* operand)
{
   MyClass sum;
   for(int i = 0; i < count; i++)
   {
      MyNode* newNode
      newNode->value = value + operand->value;
      sum->insert(newNode);
   }
   return sum;   
}

When I try to implement this in my main function like so:

MyClass* a = new MyClass();
MyClass* b = new MyClass();
MyClass* c;

c = a + b;

The compiler throws an error: "cannot add two pointers".

Are you coming from a Java background? You don't need new to create objects:

Try this:

MyClass MyClass::operator+(const MyClass& operand)
{
   MyClass result;

   // Perform addition ...

   return result;  
}

MyClass a;
MyClass b;
MyClass c;

c = a + b;

Two problems. First, your operator has a wrong signature. operator+ should take a const reference as an argument and return a const value. Thus:

const MyClass MyClass::operator+(const MyClass& operand)

Second, you're trying to add the pointers themselves rather than the objects they point to. So you need:

*c = *a + *b;

And to be 100% correct, the operator itself should be declared as a const function:

 const MyClass MyClass::operator+(const MyClass& operand) const

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM