Pra*_*ari 1 c++ class operator-overloading assignment-operator
我写了下面的类,它重载了赋值运算符.如示例所示,我*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;
}
};
Run Code Online (Sandbox Code Playgroud)
当我调用赋值运算符时a = b,就像,a.operator=(b);.
现在我正在调用一个运算符函数,这已经被传递,operator =然后为什么需要从赋值运算符返回它?
如果要支持分配链接,则必须返回*this(以及引用).例如
Class A
{
};
A x,y,z,w;
x = y = z = w; //For this you are returning *this.
Run Code Online (Sandbox Code Playgroud)
编辑更多澄清: - (回应您的评论)
假设您没有从赋值运算符返回任何内容,那么表达式将按如下方式进行计算: -
x=y=z => x=(y=z)
Run Code Online (Sandbox Code Playgroud)
以上将导致致电
y.operator(z)
Run Code Online (Sandbox Code Playgroud)
因为赋值运算符是右关联的.在接下来的电话会议之后
x.operator ( value returned from y=z) ).
Run Code Online (Sandbox Code Playgroud)
如果你没有返回任何值链接将失败.
希望我很清楚
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |