【发布时间】: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