2012-07-10 39 views
1

我不得不爲類實現循環隊列。當我測試它時,程序正確入隊和出隊。但每當我創建一個新的對象,並將其設置等於另一個,一切都打印正確,但它崩潰到了最後,以一個錯誤:執行循環隊列時出錯?

Expression: _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse) 

我跑調試器,它說這個問題是線在出列函數中。這是這個功能。

void CQUEUE::Dequeue() 
{ 
if(Isempty()) 
{ 
    cout << "Queue is empty, nothing to delete." << endl; 
    return; 
} 

if((!Isempty()) && (front == back)) //When there is only 1 item in the queue 
{         // front and back will point to the same node 
    delete front;     //but it wont be null because of that 1 item 
    front = back = 0; 
    return; 
} 

qnode *p = front; 
front = front -> next; 
delete p;//<----------DEBUGGER POINTS HERE************** 
front -> prev = back; 
return; 

} 

就像我說的,程序,直到我創建一個新的對象,併爲此

CQUEUE j = k;//Any Enqueues and Dequeues after this work, but it crashes 

這裏工作正常的拷貝構造函數櫃面這是什麼問題?

CQUEUE::CQUEUE(CQUEUE & original)//Will not compile if I put Const 
{        //in the parameter for some reason 
front = back = 0;   //So I took it out 
(*this) = original; 
front -> prev = back; 
back -> next = front; 

} 

回答

1

在你的拷貝構造函數,你做到以下幾點:

(*this) = original; 

將意味着CQUEUE jCQUEUE k都指向同一內存front指針。

void CQUEUE::Dequeue()被稱爲兩個jkdelete p;刪除存儲器,從而導致系統崩潰。

此外,您的副本構造函數必須聲明爲constCQUEUE::CQUEUE(const CQUEUE& original)。沒有更多的代碼很難說,但在你的拷貝構造函數中,你需要對指針進行深層拷貝(使用new分配內存)。閱讀What is The Rule of Three?可能會有所幫助。