C++中对象比较需通过运算符重载实现,支持成员函数或全局友元函数形式,C++20引入的<=>可自动生成比较操作,提升代码简洁性与一致性。

在C++中,对象之间的比较需要通过运算符重载来实现。默认情况下,类对象不能直接使用
==
!=
<
运算符重载允许我们为类类型定义特定运算符的行为。可以重载的比较运算符包括:
==
!=
<
>
<=
>=
以一个简单的
Point
class Point {
public:
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y) {}
// 成员函数形式重载 ==
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
// 成员函数形式重载 !=
bool operator!=(const Point& other) const {
return !(*this == other);
}
};
成员函数的左侧操作数是
*this
立即学习“C++免费学习笔记(深入)”;
某些情况下,比如希望支持隐式类型转换或对称操作(如
int + Point
class Point {
private:
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
// 声明友元函数
friend bool operator<(const Point& a, const Point& b);
friend bool operator==(const Point& a, const Point& b);
};
// 全局实现
bool operator<(const Point& a, const Point& b) {
if (a.x != b.x) return a.x < b.x;
return a.y < b.y;
}
bool operator==(const Point& a, const Point& b) {
return a.x == b.x && a.y == b.y;
}
bool operator!=(const Point& a, const Point& b) {
return !(a == b);
}
这种写法更灵活,尤其在需要对称参数类型时更自然。
C++20引入了三向比较运算符
<=>
<=>
==
!=
<
#include <compare>
class Point {
public:
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y) {}
auto operator<=>(const Point&) const = default;
};
使用
= default
auto operator<=>(const Point& other) const {
if (auto cmp = x <=> other.x; cmp != 0)
return cmp;
return y <=> other.y;
}
返回类型为
std::strong_ordering
==
const
==
!=
<
基本上就这些。合理使用运算符重载能让类的使用更直观,尤其是配合STL容器(如
std::set
std::map
<
<=>
以上就是C++如何实现对象比较与运算符重载的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号