c++运算符的重载

c++运算符重载不改变运算符的优先级和结合性。

格式为  返回类型 operator 运算符(参数列表)

输出结果

#include <iostream>
#include <string>

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 operator+ (const vector2& other) const
	{
		return add(other);
	}

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

};

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

void Log(vector2 message)
{
	std::cout << message.x << ", " << message.y << std::endl;
}

int main()
{
	vector2 speed(1.0f, 1.0f);
	vector2 position(2.0f, 2.0f);

	vector2 powerup(3.0f, 3.0f);

	vector2 result1 = position.add(speed.multiply(powerup));
	vector2 result2 = position + speed * powerup;

	std::cout << "Function Log" << std::endl;
	Log(result1);
	Log(result2);

	std::cout << "Operator << " << std::endl;
	std::cout << result1 << std::endl;
	std::cout << result2 << std::endl;

	std::cin.get();

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值