我想知道为什么重载的==函数不起作用。我对私人首脑感到困惑。私人负责人会是最后一个列出的链接列表的负责人吗?所以,如果我将最后一个链表与输入的LinkedList进行比较,它不会起作用吗?
附加代码
void LL::append(string pName,string phone)
{
Node *newNode = new Node;
newNode->name = pName;
newNode->phoneNumber = phone;
newNode->next = nullptr;
if (head == nullptr)
{
head = newNode;
}
else
{
Node *nodePtr = head;
while (nodePtr->next != nullptr)
{
nodePtr = nodePtr->next;
}
nodePtr->next = newNode;
}
}
深度复制代码
LL::LL(const LL& source)
{
head = nullptr;
Node *nodePtr = source.head;
while(nodePtr)
{
append(nodePtr->name,nodePtr->phoneNumber);
nodePtr = nodePtr->next;
}
}
main.cpp
#include <iostream>
#include "node.h"
using namespace std;
int main()
{
LL list;
list.append("jack","2");
list.append("jack2","1");
list.append("jack3","3");
list.append("jack4","4");
list.insertatBegin("notjack","0");
list.print();
list.searchByName("jack");
cout << "cloning------------------" <<endl;
LL list2(list);
//list.destroy();
//list2.append("jack","223");
list2.print();
if(list == list2)
{
cout << "same" <<endl;
}
else
{
cout << "not same" <<endl;
}
}
.h文件
#ifndef NODE_H
#define NODE_H
#include <iostream>
using namespace std;
class Node
{
public:
string name; //data
string phoneNumber;
Node* next; //pointer to next
};
class LL
{
private:
Node* head; // list header
public:
LL();
~LL();
LL(const LL& source);
void append(string pName,string phone);
void insertatBegin(string pName,string phone);
void searchByName(string pName);
void print();
void destroy();
bool operator== (const LL& L1);
};
#endif
类函数的cpp文件
bool LL::operator == (const LL &L1)
{
bool status = true;
Node *nodePtr = L1.head;
Node *nodePtr2 = head;
//cout << tmp.head <<endl;
while (nodePtr != nullptr)
{
if (nodePtr == nodePtr2)
{
nodePtr = nodePtr->next;
nodePtr2 = nodePtr2->next;
}
else
{
status = false;
}
}
return status;
}
我不知道Copy Constructor的实现是什么,如果它运行良好,那么它应该可以工作。
bool LL::operator==(const LL& L1) const{
if (&L1==this){
return true;
}
else{
Node* current = L1.head;
Node* lhs = this->head;
while(current != nullptr){
if(current->name != lhs->name || current->phoneNumber != lhs->phoneNumber)
return false;
current = current->next;
lhs = lhs->next;
}
return true;
}}