特定功能的访问冲突

时间:2015-03-17 03:31:58

标签: c++

我的CustomerList.cpp文件中有很多函数,其中唯一一个不起作用的函数如下所示(并且断点用注释标记)。注意:Store类是正确的,m_pHead是CustomerList私有变量(但这无关紧要)。

bool CustomerList::removeStore(int ID)
{

    Store *back, *temp;

    if(m_pHead = NULL)
        {
            cout << "\nError! Store " << ID << " not found in the List!\n";
            system("pause");
            return false; // nothing to delete
        }

    // Search for the item to delete
    back = NULL;
    temp = m_pHead;

    while((temp != NULL) && (temp->getStoreID() != ID))
    {
        back = temp;
        temp = temp->m_pNext;
    }

    if(back == NULL)    // Delete the first item in the list
    {
        m_pHead = temp->m_pNext; // THE FUNCTION BREAKS HERE
        delete temp;
        cout << "\nSuccess! Store " << ID << " added to List!\n";
        system("pause");
        return true;
    }
    else if(temp != NULL)  // Delete from middle or end of list
    {
        back->m_pNext = temp->m_pNext;
        delete temp;
        cout << "\nSuccess! Store " << ID << " added to List!\n";
        system("pause");
        return true;
    }
    else
    {
        cout << "\nError! Store " << ID << " not found in the List!\n";
        system("pause");
        return false;    // Didn't find the item to delete
    }

}

每次我调用这个函数时,它都会中断,即使商店的ID不在列表中(它不应该在函数中那么远)。 以下是一个电话示例:

// Creating a new Customer List
CustomerList *newList = new CustomerList();
newList->removeStore(3);

世界上我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的代码中存在一些逻辑错误。最值得注意的是,这一行;

if(m_pHead = NULL)

将<{1}}分配给NULL ,然后再进行比较。因此,m_pHead为NULL,temp保持为NULL,这就是您的代码到达您评论和崩溃的位置的原因。

您需要使用back比较运算符,而不是==赋值运算符(您的编译器应该警告过您):

=

或更安全:

if(m_pHead == NULL)

现在,如上所述,您可以将其余代码简化为以下内容:

if(!m_pHead)

或者,如果您使用标准C ++容器(例如bool CustomerList::removeStore(int ID) { Store *temp, *previous; // Search for the item to delete previous = NULL; temp = m_pHead; while (temp != NULL) { if (temp->getStoreID() == ID) { if (m_pHead == temp) { // Deleting the first item in the list m_pHead = temp->m_pNext; } if (previous != NULL) { // Deleting from middle or end of list previous->m_pNext = temp->m_pNext; } delete temp; cout << "\nSuccess! Store " << ID << " removed from List!\n"; system("pause"); return true; } previous = temp; temp = temp->m_pNext; } cout << "\nError! Store " << ID << " not found in the List!\n"; system("pause"); return false; // nothing to delete } ),而不是制作自己的手动链接列表,则可以改为:

std::list