【发布时间】:2016-10-16 19:22:54
【问题描述】:
我无法理解赋值运算符的概念,或者至少成功地创建它们。
复制构造函数对我来说不是问题;这是我的工作:
//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;
【问题讨论】:
-
否决minimal reproducible example。主题:复制构造函数中的整个潜在伤害世界:
_head = rhs._head; _tail = rhs._tail;Off 主题:注意下划线前缀。它们通常保留供内部图书馆使用。你在这里应该是安全的,但是在全局范围内这样做或在下划线后面加上大写字母,你可能会遇到麻烦。 -
叹息,感谢您的反对。大帮助
-
为什么要手动实现链表而不是使用
std::list?
标签: c++ linked-list assignment-operator