运算符 == 双链表的重载
operator == overload for double linked list
>我已经实现了双链表。现在我需要重载 == 运算符。
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);
您可以选择在类内部或外部定义它。
阅读此处,何时需要使操作员成员与非成员。
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用