尝试返回布尔值时程序崩溃

Bal*_*yOs 0 c++ boolean function

对于此代码,我的目标是更改某些函数(更像是模块化程序),以便在数据库中搜索memberNumber的任何函数都将调用返回布尔值的实际搜索函数.

现在,当searchID函数返回true时,我已经遇到程序崩溃的问题.当它返回false时它不会崩溃.

原始工作功能:

bool DonorList::searchID(int memberNumber) const
{
    bool found = false;
    list<DonorType>::const_iterator iter = donors->begin();
    while (iter != donors->end() && !found)
    {
        if (iter->getMembershipNo() == memberNumber)
        {
            found = true;
        }
        else
            ++iter;
    }
    return found;
}
Run Code Online (Sandbox Code Playgroud)

改变功能:

bool DonorList::searchID(int memberNumber) const
{
    list<DonorType>::const_iterator iter;
    bool found = searchDonorLocation(memberNumber, iter);
    return found;
}
Run Code Online (Sandbox Code Playgroud)

增加功能:

bool DonorList::searchDonorLocation(int memberNumber, list<DonorType>::const_iterator &iter) const
{
    iter = donors->begin();
    bool found = false;
    while (iter != donors->end())
    {
        if (iter->getMembershipNo() == memberNumber)
        {
            found = true;
        }
        else
            iter++;
    }
    return found;
}
Run Code Online (Sandbox Code Playgroud)

我不知道导致问题的原因是,只要新更改的函数返回true,程序就会崩溃.我已经尝试过返回searchDonorLocation(memberNumber,iter),但这会导致完全相同的崩溃.

xax*_*xon 5

while (iter != donors->end())
{
    if (iter->getMembershipNo() == memberNumber)
    {
        found = true;
    }
    else
        iter++;
}
Run Code Online (Sandbox Code Playgroud)

当它们匹配时,你的循环永远不会结束,因为你没有碰撞你的迭代器,所以它永远不会到达终点.是崩溃还是悬挂?

在原始代码中,您可以测试!found循环的退出.

while (iter != donors->end() && !found)
Run Code Online (Sandbox Code Playgroud)

  • 有些人说只在函数中调用一次返回,但是我在循环中用"return true"编写这种循环,在它之后写"return false" - 并且没有'找到'变量.人们跳过的障碍只有一个返回声明使代码更难以跟随我. (2认同)