リンクリストのコピーコンストラクタを実装しようとしています。私はコピーコンストラクタのために使用することになるだろうリストを返すコピー方法を書かれ、代入演算子のオーバーロードしました:リンクリストコピーコンストラクタと代入演算子のcopy()メソッドの使用
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++;
}
:ここでは上記で使用add()メソッドで
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;
}
を私はそうコピーコンストラクタを実装しようとしてきた:
template<class T>
SinglyList<T>::SinglyList(const SinglyList<T> &a) {
this->copy(a.head); //Does this not work?
}
私は(メインでそのようにコードを実行):
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は、既存のコードに余分な機能を追加するためのコードを変更することでした。