C++如何使函数返回调用它的对象

C++ How to make a function return the object that called it?

本文关键字:对象 调用 返回 何使 函数 C++      更新时间:2023-10-16

这感觉应该很明显,但我已经找了一段时间,肯定没有问对问题。我正在为Vector2D类进行赋值运算符重载。该函数只是将调用对象的x和y坐标转换为参数中传递的向量:

// Vector2D.h
class Vector2D
{
public:
float x, y;
Vector2D();
Vector2D(float x, float y);
.
.
.
Vector2D& operator=(const Vector2D& vec);
.
.
.
}

// Vector2D.cpp
.
.
.
Vector2D & Vector2D::operator=(const Vector2D & vec)
{
this->x = vec.x;
this->y = vec.y;
return ? ? ? ? ;
}
.
.
.

我应该返回什么来完成这项工作?我天真地以为return this;会这么做,但这不是合适的参考。

我天真地认为return this;会这么做,但这不是正确的参考。

this是指向当前对象的指针。要实现您想要的结果,只需取消引用它:*this