0

연결된 목록의 복사 생성자를 구현하려고합니다.연결된 목록 복사 생성자 및 할당 연산자에 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는 기존 코드에 추가 기능을 추가하는 코드를 수정했다.

답변

0

몇 가지 문제가 있습니다. 가장 큰 것은 무한 재귀입니다.

복사 생성자가 값으로 새 목록을 반환하는 copy 함수를 호출합니다.이 함수는 복사되어 복사 생성자가 호출됨을 의미합니다. 등등. 이 문제는 디버거을 사용하여 쉽게 발견되었을 수 있습니다. learn how to debug your programs에 시간을 할애하는 것이 좋습니다.

멤버 변수를 적절히 초기화하면 할당 연산자 (표시 한대로)를 사용하여 복사 생성자 (예 : *this = a;)를 구현할 수 있습니다.

그러나 나는 새 목록을 만들고 반환하는 대신 copy 함수를 수정하여 목록으로 다른 목록에서 복사하는 것이 좋습니다. 그 할당 연산자에 대해


... 당신은 당신이 먼저 제거해야, 현재 목록이 이미 노드가있을 때 사건에 대해 생각해야합니다.