c++ - 重载比较运算符

标签 c++ operator-overloading

我是 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 , ab .

或者,您可以定义一个实例运算符,接受一个参数并将其与当前实例进行比较:

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/

相关文章:

c++ - 计算布隆过滤器的近似种群

c++ - 使用原子指令确保映射访问安全,是否可以使用 2 个不同的原子指令重新排序?

c++ - 如何正确安装 SOCI?

c++ - 如何要求显式强制转换

c++ - 重载下标运算符导致访问冲突

c++ - 你可以使用 boost::shared_ptr 作为 map 的键吗?

c++ - 回调和 `std::recursive_mutex` - 有效用例?

c++ - Visual C++ 关系运算符重载 const 正确性(使用 std::sort)

c++ - 为什么我不能用非引用返回类型定义 operator=?

.net - 是否有启用 > < 和所有其他比较运算符的界面?