操作员的这个超载有什么问题?

时间:2014-03-17 00:21:27

标签: c++ reference operator-overloading

我有一个名为List的类,它实现了一个链表。

我正在尝试重载链表类的'+'运算符,所以我可以做这样的事情:

List l1;
/* add a and b to l1 */
List l2;
/* add c and d to l2 */
List l3 = l1 + l2;
/* l3 contains a, b, c, d and l1 and l2 are unchanged */

我已经实现了operator + = like,它似乎工作正常。

List& List::operator+=(List& otherList) {
  Node* currNode = otherList.getHead();
  while (currNode) {
    this->add(currNode->getData());
    currNode = currNode->getNext();
  }
  return *this;
}

这是我尝试实现operator +但它似乎不起作用。

List List::operator+(List& otherList) {
  List* l = new List();
  l += *this;
  l += otherList;
  return *l;
}

当我这样尝试时:

List l1;
List l2;
List l3;
l3 = l1 + l2;

我收到此错误:

Main.cc:25:13: error: no match for ‘operator=’ in ‘l3 = List::operator+(List&)((* & l2))’

任何想法我做错了什么?

更新:我还有一个看起来像这样的运算符=似乎工作正常

List& List::operator=(List& otherList);

3 个答案:

答案 0 :(得分:4)

你的operator+没有错;你显然错过了一个复制赋值操作符。

另外,停止动态分配所有内容;你像个小偷一样漏水。

答案 1 :(得分:1)

如果operator+=是正确的,那么只需执行此操作(在您的类定义之外):

List operator+(List x, List const &y) { return x += y; }

正如其他人所说,由于您正在复制对象,因此必须具有复制赋值运算符,以及复制构造函数和析构函数。 (除非默认值有效,否则我们无法确定List的定义)。

答案 2 :(得分:0)

看起来我找到了一个足够的解决方案......这对我有用:

List& List::operator+(List& otherList) {
  List* l = new List();
  *l += *this;
  *l += otherList;
  return *l;
}

感谢大家的帮助。

相关问题