复制双向链表 (c++) 的构造函数

Copy constructor of a doubly linked list (c++)

本文关键字:构造函数 c++ 双向链表 复制      更新时间:2023-10-16

我一直在为双向链表实现复制构造函数时遇到问题。我的教授为DLL类提供了一个框架,我正在将这些函数作为项目的一部分实现。我在网上看到的所有内容都没有被证明是太有帮助的,因为我看到的所有内容看起来都与我应该使用的代码格式完全不同。

对于初学者来说,这是DLL.h文件

#include <string>
using namespace std;
struct Node{
    string ssn;
    string name;
    Node* succ;
    Node* pred;
};
class DLL{
    private:
        Node* headPtr;
        int itemCount;
    public:
        DLL();
        DLL(DLL& n); //Copy constructor
        virtual ~DLL();
        Node* getHeadPtr();
        int search(string ss) const;
        bool insert(string ss, string name, int & count);
        bool remove(string ss, int & count);
        int size();
        void display();
};

除了析构函数之外,我还实现了所有其他函数,我还没有处理过,但到目前为止,这是我的复制构造函数代码:

DLL::DLL(DLL& n){
    n.headPtr = nullptr;
    n.itemCount = 0;
    Node* temp = headPtr;
    while(temp!= NULL){
        temp = temp->succ;
        insert(temp->ssn, temp->name, n.itemCount);
    }   
}

当我运行这个时,我不断得到段错误。我已经在互联网上搜索了一段时间,但没有出现任何与这种格式相似的东西让我理解。

所有帮助/建议/建议将不胜感激,谢谢!

编辑:所以现在我有了这个,它在技术上有效,但要求是内存地址不同。我得到了一个文件测试.cpp它使用示例参数运行函数,最后运行就像 Orig 列表:12、13、14(带有内存地址),然后是新复制的函数。

在我得到段错误 11 之前,但现在它正在运行,但位于相同的内存地址。

DLL::DLL(DLL& n){
Node* temp = n.headPtr;
headPtr = temp;
int count = 0;
while(temp != NULL){
    insert(temp->ssn, temp->name, count);
    temp = temp->succ;
}   

}

你在

复制构造函数中做的第一件事就是破坏原始列表。 n是您从中复制的列表,通常不应修改,这就是为什么通常复制构造函数const Type&作为输入参数的原因。

你必须做类似的事情

DLL::DLL(DLL& n) {
    int i = 0
    Node* temp = n.headPtr;
    while(temp != NULL){
        temp = temp->succ;
        insert(temp->ssn, temp->name, i++);
    }   
}