我是 C++ 的新手,正在尝试重载类中的 < 运算符。
在我的头文件中我有:
friend bool operator<(const Tweet& a, const Tweet& b);
在我的类文件中:
inline bool Tweet::operator<(const Tweet& a, const Tweet& b) {
return (a.getID() < b.getID());
}
目前我收到一个错误 ‘bool Tweet::operator<(const Tweet&, const Tweet&)’ must take exactly one argument
删除 Tweet::
将错误更改为 undefined reference 并删除第二个参数将错误更改为“必须恰好采用两个参数”
PS - 我已尝试按照 Operator overloading 中的相应部分进行操作以及一些相关的问题,但后来我遇到了各种不同的错误。
最佳答案
嗯,你是声明一个独立的函数作为友元,然后定义一个类成员函数作为比较。这并不完全正确。
如果定义有两个参数的比较运算符,则必须将其声明为静态的:
static bool Tweet::operator<(const Tweet& a, const Tweet& b) {
return (a.getID() < b.getID());
}
这边a < b
被解释为 Tweet::operator<(a, b);
.
没有static
,你隐含地得到 3 个参数:*this
, a
和 b
.
或者,您可以定义一个实例运算符,接受一个参数并将其与当前实例进行比较:
bool Tweet::operator<(const Tweet& b) {
return (getID() < b.getID());
}
这边a < b
被解释为 a.operator<(b);
.
或者,您可以定义一个独立的函数(这是您实际可能需要的地方 friend
):
bool operator<(const Tweet& a, const Tweet& b) {
return (a.getID() < b.getID());
}
这边a < b
被解释为 operator<(a, b);
.
哪种方式都好。
关于c++ - 重载比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12029872/