[英]Access violation for a specific function
我的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
}
}
每次我調用此函數時,即使Store的ID不在列表中,它也會中斷(它不應在函數中走得那么遠)。 這是一個呼叫示例:
// Creating a new Customer List
CustomerList *newList = new CustomerList();
newList->removeStore(3);
我到底在做什么錯?
您的代碼中存在一些邏輯錯誤。 最值得注意的是,這條線;
if(m_pHead = NULL)
在比較之前將NULL
分配給m_pHead
。 因此, temp
為NULL,而back
仍為NULL,這就是為什么代碼到達注釋位置並崩潰的原因。
您需要使用==
比較運算符,而不是=
賦值運算符(您的編譯器應已對此發出警告):
if(m_pHead == NULL)
或更安全:
if(!m_pHead)
現在,您可以將剩下的代碼簡化為以下代碼:
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
}
或者,如果您使用標准的C ++容器,例如std::list
,而不是創建自己的手動鏈表,則可以這樣做:
struct isStoreID
{
int m_id;
isStoreID(int id) : m_id(id) {}
bool operator()(const Store &store) { return (store.getStoreID() == m_id); }
};
bool CustomerList::removeStore(int ID)
{
// Search for the item to delete
// where m_list is a std::list<Store>...
std::list<Store>::iterator iter = std::find_if(m_list.begin(), m_list.end(), isStoreID(ID));
bool bWasFound = (iter != m_list.end());
if (bWasFound)
{
m_list.erase(iter);
cout << "\nSuccess! Store " << ID << " removed from List!\n";
}
else
cout << "\nError! Store " << ID << " not found in the List!\n";
system("pause");
return bWasFound;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.