【问题标题】:What wrong with this overload of the operator+?operator+ 的这种重载有什么问题?
【发布时间】:2014-03-17 00:21:27
【问题描述】:

我有一个名为 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+=,它似乎工作正常。

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))’

任何想法我做错了什么?

更新:我也有一个 operator= 看起来像这样并且工作正常

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

【问题讨论】:

  • 你有复制赋值运算符吗?
  • 先生,离开这段代码,休息几个小时;)
  • 另外,您对operator+ 的实现可以大大改进。特别是用基于堆栈的对象替换动态分配的内存。
  • @0x499602D2 “复制赋值运算符”是指operator=吗?如果是这样,是的,我有一个“List& List::operator=(List& otherList);”实施和工作。谢谢!
  • @MartinJ。不错的建议,但我想现在就开始工作——你认为我错过了什么很愚蠢的具体内容?

标签: c++ reference operator-overloading


【解决方案1】:

您的operator+ 没有错;您显然缺少一个复制赋值运算符。

另外,停止动态分配一切;你漏水了。

【讨论】:

    【解决方案2】:

    如果operator+= 是正确的,那么就这样做(在你的类定义之外):

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

    正如其他人所说,既然要复制对象,那么您必须有一个复制赋值运算符、一个复制构造函数和一个析构函数。 (除非默认的工作,我们不能确定没有看到List 的定义)。

    【讨论】:

    • 但是如果我这样做return x += y,我不是在改变'x'的内容吗?我的理解是(例如,int x = y + z; 它返回一个新的 int x 而不改变 yz)操作员+必须创建一个包含 x 和 y 元素的新列表。我说的对吗?
    • 不,您正在创建一个局部变量并对其进行修改,然后将其返回。参数List x 表示x 是传入参数的副本。
    【解决方案3】:

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

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

    谢谢大家的帮助。

    【讨论】:

    • operator+() 实际上不应该返回引用。这对您有什么帮助?
    猜你喜欢
    • 2011-03-25
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多