当比较结构体时,应该优先使用 const 引用参数来实现 == 运算符的重载。这是因为结构体的拷贝代价通常比较高,因此使用引用参数可以避免不必要的拷贝操作。另外,由于 == 运算符不应该修改结构体的状态,所以使用 const 修饰参数更加符合语义。
以下是使用 const 引用参数实现比较运算符的示例代码:
struct Point {
int x, y;
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};
int main() {
Point p1 {1, 2}, p2 {3, 4};
if (p1 == p2) {
printf("(%d, %d) == (%d, %d)\n", p1.x, p1.y, p2.x, p2.y);
} else {
printf("(%d, %d) != (%d, %d)\n", p1.x, p1.y, p2.x, p2.y);
}
return 0;
}