【发布时间】:2013-10-26 18:52:55
【问题描述】:
所以,我正在尝试在我正在编写的链接列表类中覆盖 operator=,但由于某种原因不断遇到这个奇怪的问题。
List& List::operator=(const List& copyList){
if(copyList.head != nullptr){
makeEmpty(); // clears *this from any previous nodes
cout << "if statement " << endl;
head = new Node; // create a new node for head
head -> data = copyList.head -> data; // copy the first data of copylist
Node* pnew = head; // a temp node to traverse the new linkedlist
assert(head != nullptr);
Node* current2 = copyList.head;
current2 = current2 -> next;
while(current2 != NULL && pnew != NULL){
cout << "entering while loop " << endl;
pnew-> next = new Node;
pnew -> next->data = current2 ->data;
cout << "pnew next data " << *(pnew -> next->data) << endl;
assert(pnew-> next != nullptr);
pnew = pnew -> next;
current2 = current2 -> next;
cout << "after current2" << endl;
}
pnew -> next = NULL;
}else{
cout << "else statement " << endl;
head = nullptr;
}
cout<< "printing out copylist"<< endl << copyList << endl;
cout<< "printing current list: " << endl << *this << endl;
return *this;
}
所以,这是我必须测试运算符覆盖的代码:
cout << "mylist:" << endl << mylist << endl;
cout << "mylist4:" << endl << mylist4 << endl;
mylist = mylist4;
cout << "mylist:" << endl;
cout << mylist << endl;
cout << "mylist4:" << endl;
cout << mylist4 << endl;
这是输出:
mylist:
10 f
16 u
20 n
25 !
mylist4:
14 s
15 t
16 u
18 f
19 f
25 !
if statement
entering while loop
pnew next data 15 t
after current2
entering while loop
pnew next data 16 u
after current2
entering while loop
pnew next data 18 f
after current2
entering while loop
pnew next data 19 f
after current2
entering while loop
pnew next data 25 !
after current2
printing out copylist
14 s
15 t
16 u
18 f
19 f
25 !
printing current list:
14 s
15 t
16 u
18 f
19 f
25 !
*crashes right here*
我已经尝试解决这个问题大约 3 天了。任何帮助将不胜感激。提前致谢!
编辑:这里是构造函数(析构函数是编译器默认的):
NodeData::NodeData(int n, char c) {
num = n; ch = c;
}
EDIT2:我仔细检查后发现了问题。问题是我没有将头的最后一个节点,即while循环之后的pnew指向null。这解决了这个问题。感谢大家的支持。
【问题讨论】:
-
您不会通过发布的代码获得该输出。首先是原因,它甚至不会编译。没有与
else匹配的if,而且我在这段代码中至少看到了两个主要 逻辑问题,这对您列表的其余部分没有太大希望。 -
哦,对不起,伙计。我编辑了它。不小心漏掉了 if 语句。
-
@EdHeal 从对 Dietmar 回答的评论来看,这是一项学术练习。
-
如果你使用编译器的默认构造函数,你的列表会泄漏内存!
标签: c++ linked-list operator-keyword