简体   繁体   English

Remove Function 使程序崩溃 C++

[英]Remove Function is making the program to crash c++

/********************************************
*   Remove the last employee from the list  *
********************************************/
void EmployeeList::Remove() 
{
    newEmployee * nextToEnd = head, 
                * last = head->Next();

    //THIS IS THE PROBLEM
    //no nodes
    if(head == NULL)
        return;

    //remove the only employee in the list
    if(head->Next()== NULL)
    {
        cout << "\n\t\tEmployee ID " << head->empID() << " and salary $" 
             << head->ySalary() << " have been removed.\n"; 
        head = NULL;
        delete head;
    }

    else
    {  
       // remove the last employee of the list
        while(last->Next() != NULL)
        {
            nextToEnd = last;
            last = last->Next();
        }   

       cout << "\n\t\tEmployee ID " << last->empID() << " and salary $" 
            << last->ySalary() << " have been removed.\n";  

        delete last;
        nextToEnd->SetNext(NULL);      
    }
}

having problem when trying to remove from an empty list.尝试从空列表中删除时出现问题。 I know i cant remove if it is empty but i would instead of crashing the program to display "The Employee List is empty.我知道我无法删除它是否为空,但我不会让程序崩溃以显示“员工列表为空。

I specified where I think the problem hoping someone can help me out to figure it out.我指定了我认为问题的位置,希望有人可以帮助我解决问题。

All you have to do is what's already shown in the code.您所要做的就是代码中已经显示的内容。 Notice how it outputs text to console using cout .注意它如何使用cout文本输出到控制台。 Change the if statement where you specified the 'problem' is to output a message and then return.将您指定“问题”的if语句更改为输出消息然后返回。

But your program crashing has nothing to do with what you have marked.但是您的程序崩溃与您标记的内容无关。 It is crashing because of head->Next() .由于head->Next()它崩溃了。 You can't call a method on an object that is NULL .您不能在NULL的对象上调用方法。 That should be occurring after the if (head == NULL) check.这应该发生if (head == NULL)检查之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM