C++运算符及其重载

在C++中运算符不仅包括+、-、*、/,还有<<、new、delete、逗号(,)、()、[]等实际上也是运算符。

C++中运算符可以被重载,在C#中部分可以,Java中则完全不可以。

重载运算符关键字:operator。operator跟上要重载的运算符,如oprator+重载+号、oprator*重载*号等等。

演示代码部分:

struct Vector2

{

float x,y;

Vector2(float x, float y)

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

Vector2 Add(const Vector2 &other) const

{

return Vector2(x+other.x, y+other.y);

}

Vector2 oprator+ (const Vector2 &other) const //重载+

{

return Add(other);

}

Vector2 Mulitply(const Vector2 &other) const

{

return Vector2(x * other.x, y * other.y);

}

Vector2 oprator*(const Vector2 &other) const //重载*

{

return Mulitply(other);

}

};

std::ostream &oprator<<(std::stream &stream, const Vector2 &other) //重载<<运算符

{

stream << other.x << ", " << other.y ;

return stream;

}

int main()

{

Vector2 position(4.0f, 4.0f);

Vector2 speed(0.5f, 1.5f);

Vector2 powerup(1.1f, 1.1f);

Vector2 result1 = position.add(speed.mulitply(powerup)); //传统方法,用函数实现加法乘法

Vector2 result2 = position + speed * powerup; //通过运算符重载实现加法乘法

std::cout << result2 <<std::endl; //需要重载<<运算符

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柊つ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值