在C++中,運(yùn)算符重載允許你自定義類的運(yùn)算符行為。對(duì)于比較操作,通常有以下幾種情況:
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
等函數(shù)對(duì)象來(lái)簡(jiǎn)化代碼。例如,重載小于運(yùn)算符:#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);
}
};
注意:在使用運(yùn)算符重載時(shí),請(qǐng)確保你的重載運(yùn)算符行為符合邏輯和預(yù)期,以避免產(chǎn)生意外的結(jié)果。