我想實現鏈接列表的複製構造函數。我已經寫了返回的將是用於拷貝構造函數和重載賦值運算符列表的複製方法:對鏈表複製構造函數和賦值運算符使用copy()方法
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是修改代碼以額外的功能添加到現有的代碼。