简体   繁体   English

实现重载运算符“+”时出错

[英]Error when implementing overloading operator “+”

I have a MyClass which is a linked list for which I have overidden the operator+: 我有一个MyClass ,它是一个链接列表,我已经覆盖了运算符+:

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: 当我尝试在我的main函数中实现它时,如下所示:

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? 你是来自Java背景吗? You don't need new to create objects: 您不需要new来创建对象:

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. operator+应该将const引用作为参数并返回一个const值。 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: 要100%正确,操作符本身应该声明为const函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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