运算符 == 双链表的重载

operator == overload for double linked list

本文关键字:重载 运算符 链表      更新时间:2023-10-16

>我已经实现了双链表。现在我需要重载 == 运算符。

DLL.cpp:67:17:错误:预期的表达式 if ([ind] != sp[ind]( {

如果只给出一个参数,我不明白如何重载 == 运算符的问题。我的意思是如果我写布尔运算符==(DLL sp1,DLL sp2({}编译器说error: overloaded 'operator==' must be a binary operator (has 3 parameters)

#include<iostream>
#include<string>
using namespace std;
template<typename T>
class DLL {
public:
DLL(){
size = 0;
head = nullptr;
tail = nullptr;
}
T operator [](int ind) {
int counter = 0;
T res = T();
Node *cur = this->head;
while(cur != nullptr) {
if(counter == ind) {
res = cur->data;
}
cur = cur->next;
counter++;
}
return res;
}
bool operator ==(DLL<int> sp){
bool isequal = true;
for(int ind = 0; ind < sp.length(); ind++){
if ([ind] != sp[ind]) {
isequal = false;
}
}
return isequal;
}
void clear() {
while(size != 1)
pop_front();
delete tail;
size--;
}
int length() {return size;}
}
private:
class Node{
public:
T data;
Node *next;
Node *prev;
Node(T data = T(), Node *prev= nullptr, Node *next = nullptr) {
this->data = data;
this->next = next;
this->prev = prev;
}
};
int size;
Node *head;
Node *tail;
};

你把它定义为成员函数的方式(由于某种原因它只接受 int 列表(你可能应该删除<int>(。

bool operator ==(DLL<int> sp);   // There is a small issue in that you
// passing by value and thus causing a copy.
// Another issue with this is that it should
// probably marked "const" to indicate state
// is not changed by the call.

当编译器看到这个时。

list1 == list2

这只是语法糖,用于:

list1.operator==(list2);

这就是为什么当您将其声明为成员函数时只需要一个参数的原因。另一种方法是将其声明为友元函数。

friend bool operator ==(DLL<T> const& lhs, DLL<T> const& rhs);

在这种情况下,它是一个独立的功能。当编译器看到:

list1 == list2

这是语法糖,用于:

operator==(list1, list2)

问题是您正在定义具有两个参数的成员函数。左边是类对象,然后你期望右手边有两个对象(但 == 运算符在右边只有一个位置(。这就是为什么它抱怨三个参数。

所以真正的问题是它应该是会员还是朋友。

这里没关系。

在某些情况下,它"可以"。

示例:如果您的类包含单个参数构造函数(假设您可以从整数创建一个列表(,并且您使用成员operator==()

DLL<int>    list;
if (list == 5) {
}

现在将编译。因为成员运算符使用参数,并且编译器可以使用单个参数构造函数将整数转换为 DLL 参数。

与此相反的论点是,通常您不希望自动转换您的类型,因此您应该将单参数构造函数标记为explicit以防止这种情况。

所以:

如果你的类可以通过一个参数构造函数自动创建(大多数情况下这不是真的,但可以(。

那么你应该更喜欢一个朋友函数版本。

否则没关系,我可能会落入成员函数。

在大多数情况下,您都在做正确的事情。

导致此错误的问题:

dll.cpp:67:17:错误:预期的表达式如果 ([ind] != sp[ind]( {

是你真的想这样做:

*this[ind] != sp[ind]

此外,这里似乎还有一个额外的}

int length() {return size;}
} // <- not exactly sure what that's about, but I don't think you need it.

比较运算符是平等对待两个操作数的二元运算符,建议将其设置为友元函数而不是成员。

因此,函数的声明将更改为

friend bool operator ==(const DLL<int> & lhs, const DLL<int> & rhs);

您可以选择在类内部或外部定义它。

阅读此处,何时需要使操作员成员与非成员。