Hi all.
I am trying to overload the operator+ for a SLinkedList class I created. I would like to write list1 = list1 + list2;
and obtaining that list2 is merged into list1.
I thought it was simple but it didn't worked properly. I tried to simplify the problem as much as I could (to isolate the causes) and this is what I've got:
template <class D>
class SLList {
SLListNode<D> *Head;
SLListNode<D> *Tail;
public:
friend class BSTree<D>;
static int Count;
string Name;
SLList(string id);
~SLList(void);
int GetCount(void);
D GetRecord(void);
bool AddRecord(D record);
void Show(void);
bool RemoveRecord(void);
bool InputRecord(int num, bool sort);
SLList<D> operator+(SLList<D> ob2);
};
template <class D>
SLList<D> SLList<D>::operator+(SLList<D> ob2) {
return *this;
}
template <class D>
SLList<D>::SLList(string id) {
Name = id;
Head = new SLListNode<D>;
Tail = Head;
Count++;
return;
}
template <class D>
SLList<D>::~SLList(void) {
SLListNode<D> *aux;
aux = Head;
while(aux!=Tail) {
Head = Head->Next;
delete aux;
aux = Head;
}
delete aux;
Count--;
return;
}
int main(void) {
SLList<int> list1("IntList1");
SLList<int> list2("IntList2");
list1.InputRecord(0, true);
list1.Show();
list2.InputRecord(0, true);
list2.Show();
list1 = list1 + list2;
cout << endl << "// here the program evaluates 'list1 = list1 + list2;' " << endl;
// from here on both list1 and list2 are all messed up
list1.Show();
list2.Show();
cin.get();
return EXIT_SUCCESS;
}
What I expected it to do was simply... nothing! I thought that the expression "list1 + list2" would have returned list1, so that "list1 = list1" shouldn't have changed anything... However both list1 and list2 are all messed up in the following .Show()s .
Here's and example output:
How many records would you like to add to the SLList 'IntList1'?
3
Please insert record [1]
1
Please insert record [2]
2
Please insert record [3]
3
The SLList 'IntList1' is:
{ 1, 2, 3 }
How many records would you like to add to the SLList 'IntList2'?
3
Please insert record [1]
4
Please insert record [2]
5
Please insert record [3]
6
The SLList 'IntList2' is:
{ 4, 5, 6 }
// here the program evaluates 'list1 = list1 + list2;'
The SLList 'IntList1' is:
{ 134525024, 134524960, 134525040 }
The SLList 'IntList2' is:
{ 134525072, 134525008, 134525088 }
Even when the operator+ overloading was effective it caused the same problem: it actually merged the two lists in the right way (I knew it for putting a Show() call from inside operator+) but after exiting the function both the list were all messed up. I think this is caused by some problem with making a copy of the object... should I overload the constructor? And if yes, any hint on "how" ?
I'm stuck :S
Anticipate thanks for every hint :)