定义一个结构体 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();
}