提问人:Esmee 提问时间:5/11/2021 更新时间:5/12/2021 访问量:45
C++ 链表删除整个列表,而不仅仅是 1 个节点
C++ Linked List removes whole list instead of just 1 node
问:
我创建了一个名为 ScanList 的链表,其中包含对象 Scan 的节点。但是,当我从链表中删除第一个扫描并关闭程序时,我在 ScanList 的析构函数处收到“访问冲突读取位置”类型的异常。
我从ScanList中删除Scan的功能如下。
bool ScanList::removeScan(int serialNumber)
{// post: IF serialNumber is present in the list
// THEN scan has been removed from it and true has been returned
// ELSE false has been returned
Scan* currentScan = scans;
Scan* previousScan = scans;
if (currentScan != NULL && currentScan->getSerialNumber() == serialNumber)
{ // if serialNumber is the first element of the linked list
*scans = currentScan->getNext();
delete currentScan;
return true;
}
while (currentScan != NULL && currentScan->getSerialNumber() != serialNumber)
{
*previousScan = currentScan;
currentScan = currentScan->getNext();
}
if (currentScan == NULL)
{ // serialNumber is not present in the list
return false;
}
// serialNumber is present in the list and is removed
previousScan->setNext(currentScan->getNext());
delete currentScan;
return true;
}
我使用复制分配运算符,但即便如此,它也会删除扫描。它确实返回正确的值,但是当我删除 currentScan 时,它也会删除 ScanList 的整个 Scan* 扫描。这是我的复制分配运算符。
Scan* Scan::operator=(const Scan* scan)
{
// check if the Scan on the left is the same as Scan on the right
if (this == scan)
{ // if they are the same, go out of the function and return
return this;
}
this->serialNumber = scan->serialNumber;
this->timesRecycled = scan->timesRecycled;
this->next = scan->next;
return this;
}
谁能告诉我我做错了什么?
答:
0赞
Esmee
5/12/2021
#1
问题解决了,我在扫描析构函数中删除了每个扫描的 nextScan,这导致整个列表被删除。感谢您的建议!
评论
*previousScan = currentScan;
Scan::operator=(const Scan* scan)
Scan& operator=(const Scan&)
*previousScan = currentScan;
previousScan = currentScan;
scans
Scan
*scans
Scan& Scan::operator=(const Scan& scan)
previousScan = currentScan