【发布时间】: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.
我不确定为什么会出现编译时错误。我的逻辑是获取右侧列表的每个元素,然后将其简单地推到左侧列表的后面。想法?
【问题讨论】:
-
如果要连接到现有列表,重载
+=会更有意义。+运算符应返回一个新列表。但是你有两个大错误:你返回一个对局部变量的引用,你似乎试图添加两个指针。 -
从错误信息来看,
mylist1和mylist2不是Lists,它们是指针。而且你不能添加指针。
标签: c++ overloading operator-keyword singly-linked-list