【发布时间】:2021-04-30 02:46:42
【问题描述】:
标题恰到好处。
// copy constructor
IntList::IntList(const IntList& source){
Node* currentNode = source.first;
first = nullptr;
while(currentNode){
append(currentNode->info);
currentNode = currentNode->next;
}
}
//Assignment operator should copy the list from the source
//to this list, deleting/replacing any existing nodes
IntList& IntList::operator=(const IntList& source){
this -> ~IntList();
this = new IntList(source);
return *this;
}
错误: intlist.cpp:26:30:错误:需要左值作为赋值的左操作数 this = new IntList(source);
析构函数正确地删除链表中的每个节点。从技术上讲,“this”是使用赋值运算符传入的任何链表。那不就当成可以设置的对象了吗?
【问题讨论】:
-
this -> ~IntList();-- 这是错误的。这不应该在你的课堂上完成。只需简单的copy/swap 成员即可,无需致电new。 -
在纯粹的机械层面上,
this是不可修改的。this = whatever;是非法的。
标签: c++