我在指定運算符的概念或至少成功創建它們時遇到了麻煩。C++中雙向鏈表的賦值運算符
複製構造函數對我來說不是問題;這裏是我的,它的工作:
//copy constructor
Set::Set(const Set &rhs){
_head = rhs._head;
_tail = rhs._tail;
//null, basically this object is 0
if(rhs._head == NULL){
_head = NULL;
_tail = NULL;
_size = 0;
}else{
_head = new Elem(*rhs._head);
_tail = new Elem(*rhs._tail);
_size = rhs._size;
Elem *prev = NULL;
Elem *curr = _head;
Elem *otherCurr = rhs._head;
int counter = 0;
while(otherCurr->next != NULL){
curr->next = new Elem(*otherCurr->next);
curr->next->prev = curr;
curr = curr->next;
otherCurr = otherCurr->next;
}
//now that we are done lets setup the tail
_tail->prev = curr;
curr->next = _tail;
}
}
我讀示例代碼,並看到一些人使用的#include <algorithm>
庫來實現它。我嘗試了,但是,似乎並沒有工作。
//assignment operator
Set& Set::operator=(const Set &rhs){
Set temp(rhs);
std::swap(temp._head,_head);
std::swap(temp._tail, _tail);
return *this;
}
但是,上述代碼無法正常工作。真正努力去掌握賦值操作符的概念。我想它基本上和你想從一個值複製到另一個值一樣。但顯然不是。如果任何人都可以告訴我如何實現這個目標,那將會很棒。
關於我的班級的一些更一般的信息,有a _head
和a _tail
指向列表的開始和結束。虛擬元素。
這裏的對象是如何構成的:
struct Elem {
ELEMENT_TYPE info;
Elem *prev, *next;
};
Elem *_head, *_tail;
int _size;
停止並關閉投票否[mcve]。關於主題:整個世界的潛在傷害在這裏複製構造函數:'_head = rhs._head; _tail = rhs._tail;'關閉主題:注意下劃線前綴。它們通常保留供內部圖書館使用。你應該在這裏安全,但在全球範圍內做這件事,或者用大寫字母跟着下劃線,你會發現自己有麻煩。 – user4581301
嘆了口氣,感謝downvote。大幫忙 –
爲什麼你要手動實現鏈表而不是使用'std :: list'? –