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

标签 c++ copy-constructor doubly-linked-list

我一直在为双向链表实现复制构造函数时遇到问题。我的教授为 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);
    }   
}

当我运行它时,我不断收到段错误。我在 Internet 上搜索了一段时间,但没有找到与此格式相似到足以让我理解的内容。

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

编辑:所以现在我有了这个,它在技术上是可行的,但要求是内存地址不同。我获得了一个文件 test.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++);
    }   
}

关于c++ - 双向链表的复制构造函数(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36051225/

相关文章:

c++ - 我是否必须使用 std::shared_ptr 删除对对象的所有引用

java - 使用 compareTo 的 while 循环出现 NullPointerException

java - 给定指针,从 LinkedList 集合中删除一个元素

一个时钟周期内的 C++ 字符串比较

c++ - C 逗号运算符的使用

c++ - 对半透明对象实现深度测试

C++ - 在创建时调用赋值运算符而不是复制构造函数

c++ - clang 和 gcc 之间对三元运算符的 const 引用地址的差异

C++11:传递值参数初始化中转换构造函数和转换函数之间的歧义?

c++复制构造函数中的用户定义成员