重载运算符&&this关键词(C++基础)

重载运算符

运算符可重载,一般用于类中对象级比如向量相乘或相加的复杂运算,重载加号、乘号、等于、不等于四种符号如下所示:

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;
	}
	bool operator!=(const Vector2& other) const {
		return !(*this == other);
		//return !operator==(other);
	}
};

	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;

重载位运算符<<,所用类似Java中的toString,如下所示:

std::ostream& operator<<(std::ostream& stream, const Vector2& other) {
	stream << other.x << "," << other.y;
	return stream;
}//类似toString方法

this关键词

听到这里的时候已经有点听不进去了,一方面是使用指针、引用和const关键字比较多有点晕,二方面是缺乏练习,然后去写了会儿力扣,结果更晕了,三方面是看到了一条语句,越看越晕。

Entity* const & const e = this;

下面两种赋值方式是相同的:

Entity* e = this;
e->x = x;
this->y = y;

还有一个骚操作,在构造函数的时候将对象内存空间释放掉了,如下:

	Entity(int x, int y) {
		//Entity* const & const e = this;
		Entity* e = this;
		e->x = x;
		this->y = y;
		Entity& e = *this;
		PrintEntity(*this);
		delete this;
	}

听了这么多就记住了,this关键词就是指针,一个指向当前对象的指针

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

想进大厂~

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

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

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

打赏作者

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

抵扣说明:

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

余额充值