我有一个链表类。 它包括一个复制构造函数:
LinkedListStorage(const LinkedListStorage &other) :root(NULL)
{
size = other.size;
count = other.count;
node *cur = other.root;
node *end = NULL;
while(cur->next != NULL)
{
node* x = new node;
x->word = cur->word;
if(!root)
{
root = x;
end = root;
}
else
{
end->next = x;
end = x;
}
cur = cur->next;
}
}
在类中,我通过一种将链表写入文件的方法来运行它,但是虽然该方法适用于原始列表,但列表的复制版本会导致访问冲突,逐句通过列表的最终条目复制的列表按预期指向 0x00000000,但是当它到达写入函数时,最后一个节点的指针最终指向 0xcdcdcdcd,在尝试复制和使用写入函数之间没有代码运行,因此它必须是复制构造函数,但我终究无法弄清楚哪里出了问题。
在此先感谢您的帮助!
最佳答案
如果没有看到类的其余部分很难说,但也许你需要初始化 x->next
,即
node* x = new node;
x->word = cur->word;
x->next = NULL;
关于c++ - 链表的复制版本溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16416609/