我试图为链表实现复制构造函数。我编写了一个复制方法,该方法返回一个列表,该列表将用于复制构造函数并重载赋值运算符:
template<class T>
SinglyList<T> SinglyList<T>::copy(Node *u) {
SinglyList<T> newList;
Node *current = u;
if (current->next==NULL) {
newList.add(current->x);
} else while (current!=NULL) {
newList.add(current->x);
current = current->next;
}
return newList;
}
使用上面使用的add()方法:
template<class T>
void SinglyList<T>::add(T x) {
Node *u = new Node(x);
if (n == 0) {
head = u;
} else {
tail->next = u;
}
tail = u;
n++;
}
我一直在努力实现复制构造函数:
template<class T>
SinglyList<T>::SinglyList(const SinglyList<T> &a) {
this->copy(a.head); //Does this not work?
}
我在main()中运行代码:
int main() {
SinglyList<int> test;
for (int i=0; i<5; i++)
test.add(i);
test.print(); //This outputs 0 1 2 3 4
SinglyList<int> test2 = test;
test2.print(); //This should output 0 1 2 3 4 but outputs a bunch of garbage numbers
return 0;
}
然后它崩溃了。我不完全确定问题是什么。它是复制构造函数还是复制方法?
关于重载赋值运算符,使用复制方法不起作用,但在重载中运行代码本身有效吗?
template<class T>
SinglyList<T>& SinglyList<T>::operator=(const SinglyList<T> &b) {
//this->copy(b.head); <---This doesn't work
Node *current = b.head;
if (current->next==NULL) {
this->add(current->x);
} else while (current!=NULL) {
this->add(current->x);
current = current->next;
}
return *this;
}
该课程的随附代码:
template<class T>
class SinglyList {
protected:
class Node {
public:
T x;
Node *next;
Node(T x0) {
x = x0;
next = NULL;
}
};
Node *head;
Node *tail;
int n;
SinglyList<T> copy(Node*);
public:
SinglyList();
SinglyList(const SinglyList<T>&);
~SinglyList() {
Node *u = head;
while (u != NULL) {
Node *w = u;
u = u->next;
delete w;
}
};
void add(T);
SinglyList<T>& operator=(const SinglyList<T>&);
void print();
};
免责声明:部分代码已从Open Data Structures解除,而HW则修改代码以向现有代码添加额外功能。