【发布时间】:2020-04-29 17:19:43
【问题描述】:
我想知道为什么我的重载 == 函数不起作用。我对私人负责人感到困惑。私有头会是最后一个链表的头吗?那么如果我将最后一个链表与输入的 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;
}
【问题讨论】:
-
这取决于您的复制构造函数。你在做深拷贝吗?
-
如果两个链表指向相同的内存,它们是否相等?还是包含相同的数据值?
-
首先,您只比较指针,我想这不是您打算做的。接下来,您应该在比较运算符中有一个循环,但只有一个 if。
-
想想两个列表相等意味着什么。如果两个列表在列表中具有相同的项目且顺序相同,则它们是相等的。现在这意味着您的
operator==必须一次遍历两个列表中的一项,检查一个列表中的项目是否与另一个列表中的相应项目相同。我相信你可以看到你写的代码没有那样做。 -
nodePtr == nodePtr2 仅当它们是同一内存中的相同节点时才为真。所以它们必须是同一个列表,而且你已经知道一个列表等于它自己。
标签: c++ linked-list operator-overloading