我在指定运算符的概念或至少成功创建它们时遇到了麻烦。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'? –