简体   繁体   English

C++ 如何让 function 返回调用它的 object?

[英]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.

相关问题 如何使函数返回指向C ++中数组或对象的指针? - How to make function return pointer to an array or object in C++? 如何使函数在不同时间调用时返回不同的字符串? C ++ - How to make a function return different strings when called at different times? C++ 如何将 object 传递和返回到从 iOS Swift 调用的 C++ function? - How to pass and return an object to a C++ function called from iOS Swift? 如何在函数内部创建对象并将其返回给main()而不使用析构函数在c ++中将其删除? - How to make an object inside a function and return it to main() without the destructor delete it in c++? 如何使我的 function 根据使用 C++ 中的模板调用的类型返回不同的结果 - How do I make my function return different results depending on type it's been called using templates in C++ 如何使函数返回指向函数的指针? (C++) - How to make a function return a pointer to a function? (C++) 如何在C ++中正确返回模板对象? - How to make proper return of templated object in C++? 调用C ++函数而不进行对象初始化 - C++ function called without object initialization 如何使函数在C ++中返回结构指针 - how to make a function return a structure pointer in c++ 如何使C ++函数返回第一行? - How to make C++ function return to its first line?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM