I have a class called List which implements a linked list.
I'm trying to overload the '+' operator of a linked list class so I can do this kind of thing:
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 */
I've implemented operator+= like so, and it appears to work fine.
List& List::operator+=(List& otherList) {
Node* currNode = otherList.getHead();
while (currNode) {
this->add(currNode->getData());
currNode = currNode->getNext();
}
return *this;
}
Here's my attempt at implementing operator+ but it doesn't appear to work.
List List::operator+(List& otherList) {
List* l = new List();
l += *this;
l += otherList;
return *l;
}
When I try it like so:
List l1;
List l2;
List l3;
l3 = l1 + l2;
I get this error:
Main.cc:25:13: error: no match for ‘operator=’ in ‘l3 = List::operator+(List&)((* & l2))’
Any ideas what I'm doing wrong?
UPDATE: I also have an operator= that looks like this and appears to work fine
List& List::operator=(List& otherList);
Your operator+
is not at fault; you are apparently missing a copy assignment operator.
Also, stop dynamically allocating everything; you're leaking like a seive.
If operator+=
is correct then just do this (outside of your class definition):
List operator+(List x, List const &y) { return x += y; }
As others have said, since you are copying your objects, you must have a copy-assignment operator, and a copy-constructor and a destructor. (Unless the default ones work, which we can't be sure about without seeing the definition of List
).
Looks like I found a solution that will suffice ... this worked for me:
List& List::operator+(List& otherList) {
List* l = new List();
*l += *this;
*l += otherList;
return *l;
}
Thanks for the help, everyone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.