为什么operator =返回* this? [英] Why does operator = return *this?

查看:159
本文介绍了为什么operator =返回* this?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想覆盖operator =,所以我可以做类似的事情

Say I want to override the operator = so I can do something like

Poly p1;  // an object representing a polynomial
Poly p2;  // another object of the same type    
p2 = p1;  // assigns all the contents of p1 to p2

然后在实现operator =的过程中,我会遇到类似这样的事情:

Then in my implementation of the operator =, I have something like this:

Poly& Poly::operator=(const Poly &source) {
    // Skipping implementation, it already works fine…
    return *this;
}

不要介意实现,它已经可以正常工作了.

Don't mind the implementation, it already works fine.

我担心的是,当您return *this时会发生什么?我知道它会返回对该对象的引用,但是会发生这种情况吗?

My concern is that what happens when you return *this? I know it returns a reference to the object but is this what happens?

p2 = &p1

推荐答案

return *this,因此您可以编写普通的复合C ++ =语句,例如:

You return *this so you can write normal compound C++ = statements like:

Poly p1; //an object representing a polynomial
Poly p2;
Poly p2;

// ...

p3 = p2 = p1;  //assigns all the contents of p1 to p2 and then to p3

因为该声明基本上是:

p3.operator=(p2.operator=(p1));

如果p2.operator=(...)不是return *this,您将没有任何意义可以传递到p3.operator=(...).

If p2.operator=(...) didn't return *this you'd have nothing meaningful to pass into p3.operator=(...).

这篇关于为什么operator =返回* this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆