2010-11-01 86 views
2

我目前正在執行鏈接列表的堆棧。當涉及重載「=」運算符時,我遇到了問題。我對做什麼非常無知。如果任何人都能指出我會朝着一個很棒的方向發展。鏈接列表堆棧操作符重載函數

//operator overload 
template <class S> 
const Stack<S>::operator=(const Stack& s) 
{ 

    if (s.isEmpty()) 
     theFront = theTop = 0 
    else 
    { 
     NodePointer temp = q->theFront; 

     while(temp != 0) 
     { 
      push(temp->data); 
      temp = temp->next; 
     } 
    } 

    return *this; 
} 

我也收到此錯誤: 堆棧,性病::分配器>> ::節點::節點(性病:: basic_string的,性病::分配器>)」在C引用:\用戶\ JOHNNY \ DESKTOP \ STACK \ INFIX_TO_RPN.OBJ

這可以通過我的操作符重載函數來修復嗎?

回答

2

在推送數據之前,您需要清空當前堆棧。您應該添加一個removeAll函數,並在賦值的頂部調用它(在檢查自賦值之後,這也是一個好主意)。否則,它看起來是正確的。所以,最終的結果將是:

//operator overload 
template <class S> 
const Stack<S>::operator=(const Stack& s) 
{ 
    // Check for self assignment 
    if (&s==this) 
     return *this; 

    // Clear the current stack 
    removeAll(); 

    // Copy all data from stack s 
    if (!s.isEmpty()) 
    { 
     NodePointer temp = q->theFront; 

     while(temp != 0) 
     { 
      push(temp->data); 
      temp = temp->next; 
     } 
    } 

    return *this; 
} 

下面是一個簡單的removeAll功能:

template <class S> 
void Stack<S>::removeAll()  
{ 
    while (s.theFront) 
    { 
     NodePointer p = s.theFront; 

     s.theFront = s.theFront->next; 
     delete p; 
    } 

    s.theTop = s.theFront; 
} 
+0

這是非常感謝你! – Johnrad 2010-11-01 01:12:11

+0

不客氣... – 2010-11-01 01:13:48

+0

你有什麼想法,爲什麼我會得到這個錯誤? (std :: basic_string ,std :: allocator >,std :: allocator >> :: Node :: Node Johnrad 2010-11-01 01:18:43

1

不用手動執行拷貝賦值運算符類,使用the copy-and-swap idiom

一旦你已經實現了一個swap()功能,爲您的類(文章到我上面鏈接提供瞭如何做到這一點的極好的描述),該operator=過載變短而簡單:

Stack& operator=(Stack rhs) 
{ 
    swap(rhs); 
    return *this; 
} 
+0

你會意識到,通過按價值傳遞rhs,即使在這裏有可能獲得的異常安全的潛在利益,你也會深刻地複製右側的每個任務。 – 2010-11-01 01:15:21

+0

@Michael:你必須複製一份。你可以選擇在值之間使用'rhs'並在函數調用中創建副本,或者通過const引用來獲取'rhs',並將其複製到賦值運算符的主體中。編譯器可能經常能夠消除以前的副本;但它肯定無法消除後者。 – 2010-11-01 01:18:04

+0

考慮如果源堆棧和目標堆棧都非常大時會發生什麼(提示:3> 2) – 2010-11-01 01:19:22