重载运算符
运算符可重载,一般用于类中对象级比如向量相乘或相加的复杂运算,重载加号、乘号、等于、不等于四种符号如下所示:
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关键词就是指针,一个指向当前对象的指针。