运算符重载(operator overload)

运算符重载(操作符重载):可以为运算符增加一些新的功能

代码示例:

class Point {
    friend Point operator+(const Point &, const Point &);
    int m_x;
    int m_y;
public:
    Point(int x, int y) :m_x(x), m_y(y) { }
    void display() {
        cout << "(" << this->m_x << ", " << this->m_y << ")" << endl;
    }
};

// 运算符(操作符)重载
Point operator+(const Point &p1, const Point &p2) {
    return Point(p1.m_x + p2.m_x, p1.m_y + p2.m_y);
}

使用

Point p1(30, 70);
Point p2(10, 40);

// 其本质 operator+(p1, p2)
Point p3 = p1 + p2

运算符重载为成员函数

class Point {
    int m_x;
    int m_y;
public:
    Point(int x, int y) :m_x(x), m_y(y) { }
    void display() {
        cout << "(" << this->m_x << ", " << this->m_y << ")" << endl;
    }
    
    // 运算符(操作符)重载
    Point operator+(const Point &point) {
        return Point(this->m_x + point.m_x, this->m_y + point.m_y);
    }
};

使用

Point p1(30, 70);
Point p2(10, 40);

// 相当于 Point p3 = p1.operator+(p2)
Point p3 = p1 + p2

==示例

bool operator==(const Point &point) {
//    if (point.m_x == this->m_x && point.m_y == this->m_y) {
//        return 1;
//    } else {
//        return 0;
//    }    
    return (point.m_x == this->m_x) && (point.m_y == this->m_y) ;
}

-示例(转成相反的数,非减号)

Point operator-() {
    return Point(-this->m_x,-this->m_y);
}

-p1对象仍然可以赋值

-(-p1);
-p1 = Point(10,20);

如果不希望返回的对象赋值加const

const Point operator-() {
    return Point(-this->m_x,-this->m_y);
}

系统+=是有返回值的,默认返回前面的变量

int a = 10;
int a = 20;
(a += b) = 1; // a == 1

运算符重载注意:

有些运算符不可以被重载,比如

有些运算符只能重载为成员函数,比如