0%

C++之运算符重载

C++不止能进行函数重载, 还能对运算符进行重载. 通过重新定义运算符, 可以使特定的类的对象执行特定的功能. 运算符重载可以增强程序的可读性.

几乎所有的运算符都可以重载. 不能被重载的运算符有., *, ::, ?.

特别地, 运算符重载不改变运算符的优先级和结合性, 并且也不改变运算符的语法结构, 单目运算符只能重载为单目运算符, 双目运算符只能重载为双目运算符.

运算符重载的实现可以使用类成员函数的方式, 也可以使用友元函数.

下面分别使用友元函数的方式重载运算符<<(且只能用友元形式重载), 使用成员函数的方式重载运算符+:

#include <iostream>
using namespace std;

class Point {
public:
    float x, y;
    Point():x(0),y(0) {
    
    }
    
    Point(float newX, float newY):x(newX),y(newY) {
    
    };
    
    friend ostream & operator<<(ostream &os, Point &p);
    Point & operator+(Point &p);
};

ostream & operator<<(ostream &os, Point &p) {
    os << "{" << p.x << ", " << p.y << "}" << endl;
    return os;
}

Point & Point::operator+(Point &p) {
    x += p.x;
    y += p.y;
    return *this;
}

int main(int argc, const char * argv[]) {
    Point p1(5,5);
    Point p2 = Point(3.3, 4.4);
    cout << "p1: " << p1 << endl;
    cout << "p1: " << p2 << endl;
    cout << "p1 + p2: " << p1 + p2 << endl;
    return 0;
}

注意, +运算之后前面的运算对象会被改变, 而后面的运算对象不会发生改变, 因此加法交换律不适用了, 也就是**(a+b) != (b+a)**.