复制双向链表 (c++) 的构造函数
Copy constructor of a doubly linked list (c++)
我一直在为双向链表实现复制构造函数时遇到问题。我的教授为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++);
}
}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为