【发布时间】:2014-11-15 03:11:41
【问题描述】:
我试图在我的复制构造函数中复制整个链表,但是我继续获得访问权限 为什么我的复制构造不能正常工作? 错误:
Unhandled exception at 0x00AE506C in program.exe: 0xC0000005: Access violation reading location 0x00000004.
复制构造函数
NodeSLList::NodeSLList(NodeSLList & list)
{
head = list.head;
IntNode *tmp = head;
cout << "copy constructor called" << endl;
int size;
size = list.GetSize();
for (int i = 1; i <= size; i++)
{
tmp->data= list.RetrieveNode(i).data;
tmp->next = list.RetrieveNode(i).next;
tmp = tmp->next;
}
}
主要
NodeSLList list2 (list1);
cout << "cout << list2 " << endl;
cout << list2 << endl;
错误发生在cout << list2 << endl;,因为 cop 构造函数没有正确复制链表。
【问题讨论】:
-
在
1开始循环有什么原因吗?在 C++ 中,第一个元素(通常)是0。另外,您是否有将节点添加到列表后面的功能?如果是这样,则复制构造函数比您编写的代码要简单得多。 -
我设置链表的方式是1到N
-
我更新了我的评论。如果你有一个添加到列表后面的函数,那么在复制构造函数中使用它。至于从 1 而不是 0 开始计数,很多时候从 1 开始是错误的来源。
标签: c++ pointers constructor linked-list copy-constructor