简体   繁体   中英

Overloading assignment operator: if we return (*this), which is a value at a pointer/address, what's right syntax for assignment operator?

Using these two previous threads as examples

First thread: Why does overloaded assignment operator return reference to class?

Second thread: Why must the copy assignment operator return a reference/const reference?

Is the return type of an overloaded assignment operator a class or a reference to a class? I have seen both:

Point& Point::operator = (const Point& sourcePoint)
{
// As in the first thread I pasted above
return *this;
}

And

Point Point::operator = (const Point& sourcePoint)
{
// As in the second thread I pasted above
return *this;
}

Which is right?

Similarly, what's the difference between:

int exFunction()
{
     int i = 5;
     int* iPtr = &i;
     return *iPtr;
}

Versus:

int& exFunction2()
{
     int j = 5;
     int* jPtr = &j;
     return *jPtr;
}

Thanks!

The two thigns are not "similar" at all.

First off, the assignment operators. They should return a reference to the object itself, so that you can use them in a chain:

Foo x, y, z;

x = y = z;   // makes y equal to z and returns a reference to self,
             // which is assigned to x

So it's always:

Foo & operator=(Foo const &) { /* ... */  return this; }  // copy-assignment

Foo & operator=(/* any other signature */) { /* ... */   return this; }

Now, the second question: Your exFunction2 is completely wrong and broken. It has undefined behaviour, because it returns a reference to a local variable, which is out of scope by the time the function returns. (It says essentially return j; ; remember that the result of a dereference is an lvalue.) The only sensible way to write that function is like exFunction , which can be shortened to int exFunction() { return 5; } int exFunction() { return 5; } .

Here is a related question on this topic.

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