运算符重载

运算符重载是什么:
重新赋予运算符新含义,添加参数或创建,允许在程序中定义或修改运算符的行为 类似函数一样。
重载位置:在类中写相当于
举例:要实现两个向量相加

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);
	}
};
int main()
{
	Vector2 one(3.9f, 1.1f);
	Vector2 two(1.1f, 2.9f);
	Vector2 result = one.Add(two);

实现两个Vector2变量相乘
代码示例:

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 Multiply(const Vector2& others)//新实现的乘法函数
	{
		return Vector2(x * others.x, y * others.y);
	}

为了实现加法和乘法,重载 + 和 *
代码示例:

Vector2 operator +(const Vector2& other)
{
	return Vector2(x + other.x, y + other.y);
}

Vector2 operator *(const Vector2& others)
{
	return Vector2(x * others.x, y * others.y);
}
a+c相当于 a.+(c)//这么写只是方便理解 不能作为代码使用
posted @ 2024-07-14 09:38  Wzline  阅读(1)  评论(0编辑  收藏  举报