[英]C++ How to make a function return the object that called it?
这感觉应该很明显,但我已经看了一段时间,一定不能正确地问这个问题。 我正在为 Vector2D class 执行赋值运算符重载。 function 只是将调用对象的 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
是指向当前 object 的指针。 要达到您想要的结果,只需取消引用它: *this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.