操作运算符

定义一个结构体 struct Vector2 ,提供了类之间的加法、乘法操作,代码如:Vector2 result1 = position.Add(speed.Multiply(powerup));
为了将其简化为 Vector2 result2 = position + speed * powerup ; 使用operator关键词重载 ‘+’,‘*’,这两个运算符,其本质还是函数。


代码:

#include <iostream>
#include "Log.h"

using String = std::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);
	}

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

std::ostream& operator<<(std::ostream& 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.Multiply(powerup));
	Vector2 result2 = position + speed * powerup ;
	
	std::cout << result2 << std::endl;

	std::cin.get();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值