在C++中,运算符重载允许你自定义类的运算符行为。对于比较操作,通常有以下几种情况:
class MyClass { public: int value; MyClass(int v) : value(v) {} bool operator==(const MyClass& other) const { return value == other.value; } bool operator!=(const MyClass& other) const { return value != other.value; } }; class MyClass { public: int value; MyClass(int v) : value(v) {} bool operator<(const MyClass& other) const { return value < other.value; } bool operator>(const MyClass& other) const { return value > other.value; } bool operator<=(const MyClass& other) const { return value <= other.value; } bool operator>=(const MyClass& other) const { return value >= other.value; } }; std::cmp_less、std::cmp_greater等函数对象来简化代码。例如,重载小于运算符:#include <functional> class MyClass { public: int value; MyClass(int v) : value(v) {} bool operator<(const MyClass& other) const { return std::cmp_less(value, other.value); } }; 注意:在使用运算符重载时,请确保你的重载运算符行为符合逻辑和预期,以避免产生意外的结果。