[英]C++ How to make a function return the object that called it?
This feels like it should be obvious but I have looked for a while and must not be asking the question right.这感觉应该很明显,但我已经看了一段时间,一定不能正确地问这个问题。 I am doing an assignment operator overload for a Vector2D class.
我正在为 Vector2D class 执行赋值运算符重载。 The function just converts the calling object's x and y coordinates to the vector passed in the argument:
function 只是将调用对象的 x 和 y 坐标转换为参数中传递的向量:
// Vector2D.h
class Vector2D
{
public:
float x, y;
Vector2D();
Vector2D(float x, float y);
.
.
.
Vector2D& operator=(const Vector2D& vec);
.
.
.
}
and和
// Vector2D.cpp
.
.
.
Vector2D & Vector2D::operator=(const Vector2D & vec)
{
this->x = vec.x;
this->y = vec.y;
return ? ? ? ? ;
}
.
.
.
What am I supposed to return to make this work?我应该返回什么来完成这项工作? I naively thought
return this;
我天真地想把
return this;
would do it but that is not the proper reference.会这样做,但这不是正确的参考。
I naively thought
return this;
我天真地想把
return this;
would do it but that does not the proper reference.会这样做,但这不是正确的参考。
this
is a pointer to the current object. this
是指向当前 object 的指针。 To achieve your desired result, simply dereference it: *this
.要达到您想要的结果,只需取消引用它:
*this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.