简体   繁体   中英

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. The function just converts the calling object's x and y coordinates to the vector passed in the argument:

// 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; would do it but that is not the proper reference.

I naively thought return this; would do it but that does not the proper reference.

this is a pointer to the current object. To achieve your desired result, simply dereference it: *this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM