Skip to the content.

041-运算符及其重载

运算符包括加减乘除,还有一些常用的逆向引用运算符、箭头运算符、+=、&、»、还有new、delete都是运算符,甚至还有逗号运算符、括号运算符(方的圆的)

c++支持对各种运算符进行重载

在没有重载的情况下

#include <iostream>

struct Vector2 {
    float x;
    float y;

    Vector2(float x, float y) : x(x), y(y) {}

    Vector2 add(const Vector2 &vector) const {
        return Vector2(x + vector.x, y + vector.y);
    }

    Vector2 multiply(const Vector2 &vector) const {
        return Vector2(x * vector.x, y * vector.y);
    }
};

int main() {
    Vector2 position = Vector2(4.0f, 4.0f);
    Vector2 speed = Vector2(0.5f, 1.5f);
    Vector2 powerUp = Vector2(1.1f, 1.1f);
    Vector2 result = position.add(speed.multiply(powerUp));
    return 0;
}

在Java中,我们也只能这样写,但是现在是在C++中,我们可以使用运算符重载

#include <iostream>

struct Vector2 {
    float x;
    float y;

    Vector2(float x, float y) : x(x), y(y) {}

    Vector2 add(const Vector2 &vector) const {
        return Vector2(x + vector.x, y + vector.y);
    }

    Vector2 multiply(const Vector2 &vector) const {
        return Vector2(x * vector.x, y * vector.y);
    }

    /**
     * 对+进行重载
     */
    Vector2 operator+(const Vector2 &vector) const {
        return add(vector);
    }

    /**
     * 对*进行重载
     */
    Vector2 operator*(const Vector2 &vector) const {
        return multiply(vector);
    }
};

int main() {
    Vector2 position = Vector2(4.0f, 4.0f);
    Vector2 speed = Vector2(0.5f, 1.5f);
    Vector2 powerUp = Vector2(1.1f, 1.1f);
    Vector2 result1 = position.add(speed.multiply(powerUp));
    //这样更容易看
    Vector2 result2 = position + speed * powerUp;
    return 0;
}

如果我们想进行输出,我们可以调用std::cout<<但是库函数并没有针对我们自己的类进行重载,我们可以对«进行一次重载,像这样

std::ostream &operator<<(std::ostream &stream, const Vector2 &vector2) {
    stream << vector2.x << "," << vector2.y;
    return stream;
}

int main() {
    Vector2 position = Vector2(4.0f, 4.0f);
    Vector2 speed = Vector2(0.5f, 1.5f);
    Vector2 powerUp = Vector2(1.1f, 1.1f);
    Vector2 result1 = position.add(speed.multiply(powerUp));
    //这样更容易看
    Vector2 result2 = position + speed * powerUp;
    std::cout << result2 << std::endl << result1 << std::endl;
    return 0;
}

在Java中,想要比较了两个对象是否相等,我们需要重写equals方法,但是在c++中,我们可以重载操作符==,像下面这样

bool operator==(const Vector2 &vector) const {
    return x == vector.x && y == vector.y;
}

之后直接调用==比较即可

不相等呢?也可以

bool operator!=(const Vector2 &vector) const {
    return !(*this == vector);
}

https://www.bilibili.com/video/BV17X4y1M7Vb