所以,我正在尝试在我正在编写的链接列表类中覆盖 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。这解决了这个问题。感谢大家的支持。