C++运算符重载

运算符

  • 什么是operator(运算符)?基本上就是一种我们用来代替函数执行某种事情的符号。常见运算符如+,-,*,/

  • 不仅是数学运算符,也会有其它常用的运算符,比如‘&’,dereference(解引用)运算符,->箭头运算符, += 运算符,取址运算符,左移运算符( << )

  • 还有一些其它的你可能根本就没把它当成运算符的东西,比如new 和delete ,它们实际也是运算符。除此之外,逗号也可以是运算符,括号也可以是。

  • overload重载这个术语本质就是给运算符重载赋予新的含义,或者添加参数,或者创建允许在程序中定义或更改运算符的行为。

  • 说到底,运算符就是function,就是函数。与其写出函数名add ,你只用写一个+ 这样的运算符就行,有助于让你的代码更干净整洁,可读性更好。

#include<iostream>
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 Mutiply(const Vector2& other)const{
		return Vector2(x*other.x, y*other.y);
	}
};
int main()
{
	Vector2 position(4.0f,4.0f);
	Vector2 speed(0.5f,1.5f);
	Vector2 powerup(1.1f,1.1f);
	
	Vector2 result=position.Add(speed.Mutiply(powerup));
	std::cin.get();
} 

这里result 看起来有点难读,如果在Java这样的语言中这是唯一的方法。不过再C++中我们有运算符重载,这意味着我们可以利用这些运算符,并定义我们自己的运算符。

#include<iostream>
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 Mutiply(const Vector2& other)const{
		return Vector2(x*other.x, y*other.y);
	}
 
	Vector2 operator+(const Vector2& other)const{
		return Add(other);
	}
	Vector2 operator*(const Vector2& other)const{
		return Mutiply(other);
	}
	void ShowResult(){
		std::cout<<this->x<<','<<this->y<<std::endl;
	}
};
int main()
{
	Vector2 position(4.0f,4.0f);
	Vector2 speed(0.5f,1.5f);
	Vector2 powerup(1.1f,1.1f);
	
	Vector2 result=position.Add(speed.Mutiply(powerup));
	result.ShowResult();
	
	Vector2 result2=position+speed*powerup;
	result2.ShowResult(); 
	std::cin.get();
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿波茨的鹅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值