C++While循环在单个函数调用中重复调用

C++ While loop repeatedly called within a single function call

本文关键字:调用 函数调用 循环 单个 C++While      更新时间:2023-10-16

我正在调用一个函数来深度复制一个双链表。我用调试器进行了调试,一切都很完美。错误发生在一切顺利之后:第一个while循环被再次调用。我已经确保这不是函数被重复调用或其他任何情况。我对编程还相当陌生,所以我希望我只是错过了一些简单的东西。

编辑:为了澄清我的问题:在调试器中逐步运行时,执行光标从第二个while循环的开始跳到第一个while环路的开始。(第16行到第7行)在末尾添加返回时,它从返回(第24行)跳到第一个while循环(第7行

void DblLinkedList::DeepCopy(DblLinkedList &source) 
{
    Node *tempCur   = source.current; //temporary holder to reset source's current
    source.current = source.first;
    while(source.current != NULL) // traverse source list and copy each value into empty list
    {
        InsertItem(source.current->data);
        source.current = source.current->succ; // iterate source list
    } 
    source.current = source.first;
    current = first;
    while(source.current != tempCur) //setting the new`enter code here` list's current to the correct node
    {
        source.current = source.current->succ;
        current = current->succ;
        if(source.current == tempCur)
            return; //unnecessary return that doesn't fix anything
    }
return; //unnecessary return that doesn't fix anything
}

不能100%确定这是否真的算是一个答案,但我发现我的函数实际上工作正常。听从评论者的建议会有所帮助!

真正的错误发生在重载的"="运算符调用DeepCopy时。当重载函数return *this;中的最后一行运行时,它会再次调用DeepCopy(),这就是错误发生的地方。我不知道如何避免这个错误,也不知道为什么return *this首先调用DeepCopy()

rhs和lhs表示操作员的"右侧/左侧"

(我在这里很新,最好发布第二个关于这方面的问题线索吗?还是保持原样)

DblLinkedList DblLinkedList::operator=(DblLinkedList &rhs)
{
    if(this != &rhs)//if they aren't the same list
    {
        //delete original lhs list
        this->~DblLinkedList();
        //make lhs a copy of rhs
        DeepCopy(rhs);
    }
    return *this;
}