C++重载比较操作符

C++可以通过重载比较运算符来自定义对象之间的比较行为。常用的比较运算符包括==、!=、<、<=、>和>=。

例1,

#include 
using namespace std;
 
class MyClass {
private:
    int value;
public:
    MyClass(int v) : value(v) {}
    
    // 重载 == 运算符
    bool operator== (const MyClass& other) const {
        return this->value == other.value;
    }
    
    // 重载 != 运算符
    bool operator!= (const MyClass& other) const {
        return !(*this == other);
    }
};
 
int main() {
    MyClass obj1(15);
    MyClass obj2(117);
    
    if (obj1 == obj2) {
        cout << "obj1 and obj2 are equal." << endl;
    } else {
        cout << "obj1 and obj2 are 

你可能感兴趣的:(VC++,c++,开发语言,运算符重载,比较操作符重载)