【问题标题】:C++ operator+ overload singly linkedlistC++ 运算符+重载单链表
【发布时间】:2013-10-01 05:30:20
【问题描述】:

我正在尝试为链表编写一个运算符重载,它将采用 + 的右侧并将该链表连接到左侧的列表。

类声明:

 List<T>& operator+(const List<T>& right);

方法:

template <typename T>
List<T>& List<T>::operator+(const List<T>& right){
    List result(*this);
    while(right->next != NULL){
         result->push_back(right->data);
    }
    return list;
}

司机:

mylist + mylist2; //both list objects already created.

错误信息:

 Error: The operation "List<std::string>* + List<std::string>*" is illegal.

我不确定为什么会出现编译时错误。我的逻辑是获取右侧列表的每个元素,然后将其简单地推到左侧列表的后面。想法?

【问题讨论】:

  • 如果要连接到现有列表,重载+= 会更有意义。 + 运算符应返回一个新列表。但是你有两个大错误:你返回一个对局部变量的引用,你似乎试图添加两个指针。
  • 从错误信息来看,mylist1mylist2 不是Lists,它们是指针。而且你不能添加指针。

标签: c++ overloading operator-keyword singly-linked-list


【解决方案1】:

您报告的确切错误可能在您未显示的代码中,但重要的是要指出operator+ 不应返回引用。你需要一个会员运营商

List<T> operator+(const List<T>& right);

或非会员版本,

template <typename T>
List<T> operator+(const List<T>& lhs, const List<T>& rhs);

您可以根据成员+= 运算符来实现,将lhs 的元素附加到*this 并通过引用返回*this。你的例子中的逻辑有缺陷,我让你来解决这个问题,但这是一般形式:

List<T>& operator+=(const List<T>& rhs)
{
  // append elements from rhs into *this
  ....
  return *this;
}

您的operator+ 实现就变得非常简单:

template <typename T>
List<T> operator+(const List<T>& lhs, const List<T>& rhs)
{
  List<T> tmp = lhs;
  tmp += rhs;
  return tmp;
}

【讨论】:

  • 所以我明白我需要重载 operator+ 和 operator+= 才能正确连接两个列表?
  • @user1822789 你没有使用operator+=来实现operator+,但通常这样做是有意义的。
猜你喜欢
  • 2012-03-23
  • 1970-01-01
  • 2016-02-24
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 2013-11-17
相关资源
最近更新 更多