Problems with infinite loop in operator= function
Nov 4, 2010 at 7:21pm UTC
My code is below, the problem appears to be in line 98 where I have "head = c.head" which forms a loop. I don't want it to call Set(Set) again, I just want to use a "normal" equals operator. I cannot find any good examples online of how to modify my code to make it work, and any help would be appreciated. Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
#include <iostream>
using namespace std;
struct intlist
{
int element;
intlist *next;
};
class Set {
private :
intlist *head;
public :
Set();
Set(const Set &);
void insert(int x);
Set operator =(const Set &);
friend ostream & operator <<(ostream &os, const Set &s);
};
int main()
{
Set x;
x.insert(4);
x.insert(5);
cout << x << endl;
Set y = x;
cout << y << endl;
y.insert(6);
cout << x << endl;
cout << y << endl;
}
Set::Set()
{
cout << "set called" << endl;
head = NULL;
}
Set::Set(const Set &s)
{
cout << "set(Set) called" << endl;
head = NULL;
*this = s;
}
void Set::insert(int x)
{
cout << "insert called" << endl;
intlist *temp, *temp2;
if (head == NULL)
{
head = new intlist;
head->element = x;
head->next = NULL;
}
else
{
temp = head;
temp2 = new intlist;
while (temp->next != NULL)
temp = temp->next;
temp2->element = x;
temp2->next = NULL;
temp->next = temp2;
}
}
Set Set::operator =(const Set &s)
{
cout << "operator= called" << endl;
if (this != &s)
{
intlist *temp;
Set c;
while (head != NULL)
{
temp = head->next;
delete head;
head = temp;
}
temp = s.head;
while (temp != NULL)
{
c.insert(temp->element);
temp = temp->next;
}
head = c.head; // this is the problem, it calls Set(Set) again and forms a loop
}
return *this ;
}
ostream & operator <<(ostream &os, const Set &s)
{
cout << "operator<< called" << endl;
intlist *temp;
temp = s.head;
os << "{" ;
while (temp != NULL)
{
os << temp->element;
if (temp->next != NULL)
os << ", " ;
temp = temp->next;
}
os << "}" ;
return os;
}
Last edited on Nov 4, 2010 at 7:21pm UTC
Topic archived. No new replies allowed.