2012-04-09 218 views
0

我試圖使用重載操作符方法將一個隊列的條目複製到另一個隊列中,但我的功能出錯了。我不知道怎麼回事訪問隊列「原始」的任何其他方式的價值比我有如下:隊列C++的操作符重載

struct Node 
{ 
    int item; 
    Node* next; 
}; 

class Queue 
{ 
public: 
    // Extra code here 
    void operator = (const Queue &original); 
protected: 
    Node *front, *end; 
}; 

void Queue::operator=(const Queue &original) 
{ 
    //THIS IS WHERE IM GOING WRONG 
    while(original.front->next != NULL) { 
     front->item = original.front->item; 
     front->next = new Node; 
     front = front->next; 
     original.front = original.front->next; 
    } 
} 
+3

已經有一個'std :: queue'類。 – Griwes 2012-04-09 23:27:20

回答

1
void Queue::operator=(const Queue &original) 
{ 
    Node* tmp = original.front; 
    //THIS IS WHERE IM GOING WRONG 
    while(tmp->next != NULL) { 
     front->item = tmp->item; 
     front->next = new Node; 
     front = front->next; 
     tmp = tmp->next; 
    } 
} 
+0

不是我正在做什麼? – Josh 2012-04-09 23:31:24

+0

不可以。你總是在你的版本中修改前面的內容。在上面的版本中,在開始之前修改,而不是在循環中,所以前面沒有改變,並指向隊列的開始。 – Glenn 2012-04-09 23:39:19

+0

phew,我認爲這個想法很簡單 - 你修改的內容有所不同。在你的例子中,你改變了引用中的對象,在我看來你有自己的變量,你可以改變 – nothrow 2012-04-09 23:43:04

3

你有一個功能拷貝構造函數?如果是的話,我會實現你的賦值運算符在你的拷貝構造函數而言,像這樣:

#include <algorithm> // <utility> for C++11 

void Queue::operator=(const Queue &other) 
{ 
    // Assumes your only field is the "front" pointer. 

    Queue tmp(other); // May throw. 
    std::swap(front, tmp.front); // Will not throw. 
} 

的想法是,你在一旁進行,可以拋出一個異常(如您的來電operator new())的任何操作一個臨時對象,將清理資源,然後通過在非拋出操作中交換內容來「提交」您的更改,以便即使在構建tmp期間拋出異常,Queue的狀態也是正常的。保證指針分配不會丟失,這就是爲什麼在這種情況下對std::swap()的調用不會拋出。由於front與舊的front交換,因此離開作業操作員的範圍tmp的析構函數應該清理舊的鏈接列表。

請參閱GotW #59瞭解有關此「複製到臨時和交換」成語的詳細信息,以及它如何與強大的異常安全保證相關聯。