在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,并使用重載的運算符來比較它們的大小。