在C++中,可以通过重载运算符来实现Point对象的比较函数。以下是一个示例代码:
#include <iostream>
class Point {
public:
int x, y;
Point(int x, int y) : 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);
}
bool operator<(const Point& other) const {
if (x == other.x) {
return y < other.y;
}
return x < other.x;
}
};
int main() {
Point p1(2, 3);
Point p2(2, 4);
if (p1 == p2) {
std::cout << "p1 is equal to p2\n";
} else {
std::cout << "p1 is not equal to p2\n";
}
if (p1 < p2) {
std::cout << "p1 is less than p2\n";
} else {
std::cout << "p1 is not less than p2\n";
}
return 0;
}
在上面的代码中,我们定义了一个Point类,并重载了相等运算符==
、不相等运算符!=
和小于运算符<
。通过重载这些运算符,我们可以对Point对象进行比较操作。在主函数中,我们创建了两个Point对象p1和p2,并使用重载的运算符来比较它们的大小。