作为成员函数重载
class Point {
public:
int x;
int y;
Point(int a = 0, int b = 0) : x(a), y(b) {}
bool operator<(const Point& other) const {
if (x!= other.x) {
return x < other.x;
} else {
return y < other.y;
}
}
bool operator>(const Point& other) const {
return other < *this;
}
};
作为全局函数重载(结合友元函数)
class Point {
public:
int x;
int y;
Point(int a = 0, int b = 0) : x(a), y(b) {}
friend bool operator<(const Point& p1, const Point& p2);
friend bool operator>(const Point& p1, const Point& p2);
};
bool operator<(const Point& p1, const Point& p2) {
if (p1.x!= p2.x) {
return p1.x < p2.x;
} else {
return p1.y < p2.y;
}
}
bool operator>(const Point& p1, const Point& p2) {
return p2 < p1;
}
在容器中使用重载的<
和>
运算符(以set
容器为例)
#include <iostream>
#include <set>
int main() {
std::set<Point> s;
s.insert(Point(1, 2));
s.insert(Point(3, 4));
s.insert(Point(1, 3));
for (const auto& p : s) {
std::cout << "(" << p.x << ", " << p.y << ")" << std::endl;
}
return 0;
}