C++ 链表删除整个列表,而不仅仅是 1 个节点

C++ Linked List removes whole list instead of just 1 node

提问人:Esmee 提问时间:5/11/2021 更新时间:5/12/2021 访问量:45

问:

我创建了一个名为 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;
}

谁能告诉我我做错了什么?

C++ 链表 析构函数 赋值运算符

评论

1赞 Scheff's Cat 5/11/2021
有关:这确实编译没有投诉?要么是您的问题中的错别字,要么是您要求的可能问题。再读一遍你的问题,我倾向于后者。(你乞求这个。惯用赋值运算符应为 。然后会被识别为编译器错误。我很确定你的实际意图是.*previousScan = currentScan;Scan::operator=(const Scan* scan)Scan& operator=(const Scan&)*previousScan = currentScan;previousScan = currentScan;
0赞 Tim Randall 5/11/2021
什么?它是指向 ?如果是这样,那么当你给一个值时,你打算做什么?scansScan*scans
0赞 Esmee 5/11/2021
@TimRandall scans 确实是指向 Scan 的指针,但为 *scans 分配值是设置链表的第一个元素,因为删除了原始的第一个元素。
0赞 Esmee 5/11/2021
@Scheff 当我将赋值运算符更改为 and 也更改为 时,它仍然崩溃。.Scan& Scan::operator=(const Scan& scan)previousScan = currentScan
1赞 trincot 5/12/2021
请更新您的问题并添加创建列表的代码,然后调用此函数,从而触发错误。我们应该获得足够的代码来重现错误。

答:

0赞 Esmee 5/12/2021 #1

问题解决了,我在扫描析构函数中删除了每个扫描的 nextScan,这导致整个列表被删除。感谢您的建议!