+ 1
c++ +operator overload
I am try to implement +operator overload for a singly linked list in c++ so I can assign to a new list the sum of 2 list. exemple: a = [1 -> 2 -> 3 -> 4] b = [ 5 -> 6 -> 7 -> 8] c = a + b // c = [6->8->9->12] https://code.sololearn.com/cmo96v61P4MT/#cpp can someone help me debug this code?
6 Answers
+ 3
For this you will need an assignment constructor, that means you have to overload `operator=`. It will probably involve changing the pointer to your head node.
There are a few pit-falls, especially self-assignment, like `l3 = l3` - make sure this doesn't crash your code. Also consider what happens when `l1 + l2` runs out of scope and the destructor is called. Will `l3` still function?
It's probably best to look up some sample codes online!
+ 4
Your operator+ only works for Llist, not Llist*. Try stack-allocating your Llists:
int main(){
Llist l1, l2;
for(int i = 0; i<5; i++){
l1.add_tail(i);
l2.add_tail(i);
}
Llist l3 = l1 + l2;
return 0;
}
+ 3
Nope! overloading + for pointers doesn't work.
But in this case it's not a big deal as all of your nodes are allocated dynamically anyway. Only the Llist struct, a single pointer to the head node, will be on the stack if you stack allocate.
+ 2
Is there a way to do it with dynamic allocation?
+ 1
I changed the code a bit and now it's working somehow. https://code.sololearn.com/cmo96v61P4MT/#cpp
The only problem is that when I declare the object and then assign to + operation its not working.
Something like this:
LList l3;
l3 = l1 + l2;
0
thanks