gpt4 book ai didi

c++ - this还在传的时候为什么要返回*this?

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:16 25 4
gpt4 key购买 nike

我编写了以下具有重载赋值运算符的类。如示例中所示,我从赋值运算符处返回了 *this

class Sample
{
int *p;
int q;

public:

Sample()
{
cout<<"Constructor called"<<endl;

p = new int;
q = 0;
}


Sample& Sample::operator =(const Sample &rhs)
{
cout<<"Assignment Operator"<<endl;

if(this != &rhs)
{
delete p;

p = new int;
*p = *(rhs.p);
}

return *this;
}

void display()
{

cout<<"p = "<<p<<" q = "<<q<<endl;
}
};

当我像 a = b 这样调用赋值运算符时,它就像 a.operator=(b);

现在我正在调用 a 的运算符函数,这已经通过 operator = 传递,那么为什么需要从赋值运算符返回它?

最佳答案

如果你想支持赋值链,你必须返回 *this(也通过引用)。例如

Class A
{
};

A x,y,z,w;
x = y = z = w; //For this you are returning *this.

为进一步澄清而编辑:-(回应您的评论)

假设您没有从赋值运算符返回任何内容,那么表达式将按如下方式计算:-

x=y=z  =>   x=(y=z)

以上将调用

y.operator(z)

因为赋值运算符是右结合的。在此之后,下一个电话将是

x.operator ( value returned from y=z) ).

如果您不返回任何值(value)链都会失败。

希望我清楚

关于c++ - this还在传的时候为什么要返回*this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26337058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com