C++ 运算符重载

运算符重载

运算符重载也是简化代码的一个方式。例如如下代码,向量类的和与积运算在符号+和*是没有定义过的,但是通过运算符重载可以让+和*实现向量类之间的运算。

另外,如果不重载运算符,类或者其他地方就要写相关的函数(add、mutiply)来实现功能,在使用函数的时候名称会极其复杂(例如a1+a2*a3必须写成a1.add(a2.mutiply(a3)),不利于理解)

如下代码实现了+,*,==,!=,<<的重载。

#include <iostream>
using namespace std;

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

    Vector2 operator+(const Vector2& other) const
    {
        return Vector2(x + other.x, y + other.y);
    }

    Vector2 operator*(const Vector2& other) const
    {
        return Vector2(x * other.x, y * other.y);
    }

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

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

// 输出流重载不属于类
ostream& operator<<(ostream& stream, const Vector2& other)
{
    stream << other.x << ',' << other.y;
    return stream;
}

int main()
{
    Vector2 v1(1, 2);
    Vector2 v2(2, 2);
    Vector2 result1 = v1 * v2 + v1;
    if (v1 != v2)
        cout << result1 << endl;
}

重载的写法与普通函数一样,注意返回值与参数的类型,函数名就是operator<运算符>,函数体实现功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值