簡體   English   中英

對鏈表副本構造函數和賦值運算符使用copy()方法

[英]Using a copy() method for a linked list copy constructor and assignment operator

我正在嘗試為鏈表實現副本構造函數。 我編寫了一個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;
}

然后它崩潰了。 我不確定是什么問題。 是使用復制構造函數還是復制方法?

關於重載賦值運算符,使用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();
};

免責聲明:此代碼中的某些是從開放數據結構中刪除的,硬件是修改代碼以向現有代碼添加額外的功能。

有一些問題,最大的問題是無限遞歸。

您的復制構造函數調用copy函數,該函數按值返回一個新列表,這意味着將對其進行復制並調用復制構造函數。 等等等等。 使用調試器可以很容易地檢測到此問題。 我建議您花一些時間來學習如何調試程序

通過正確初始化成員變量,您可以使用賦值運算符(如您所示)來實現復制構造函數,例如*this = a;

但是,我寧願建議您修改copy功能以從另一個列表復制到列表中,而不是創建一個新列表並返回它。


關於該賦值運算符...您必須考慮當前列表中已經節點的情況,您必須首先將其刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM