연결된 목록의 복사 생성자를 구현하려고합니다.연결된 목록 복사 생성자 및 할당 연산자에 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++;
}
: 여기에 위의 사용 추가() 방법을
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;
}
그런 다음 충돌합니다. 나는 그 문제가 무엇인지 완전히 확신하지 못한다. 복사 생성자 또는 복사 방법과 함께 있습니까?
할당 연산자가 오버로드되는 것과 관련하여 copy 메서드를 사용하면 오버로드에서 코드 자체가 실행되지 않고 작동합니다. 클래스의
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는 기존 코드에 추가 기능을 추가하는 코드를 수정했다.