对于两个或多于两个对象的C ++中的重载赋值运算符? [英] Overloaded Addition assignment operator in C++ for two /more than two objects?
问题描述
我已将此运算符重载。
class sample
{
private :
int x;
public :
sample(int x1 =0)
{
x = x1;
}
sample operator+(sample s);
};
sample sample::operator+(sample s)
{
x = x + s.x;
return *this;
}
int main()
{
sample s1(10);
sample s2;
s2 = s2 + s1;
return 0;
}
这是否正确?
我的问题是如果我想添加两个不同的示例对象如何重载opeartor; s = s1 + s2
;
推荐答案
使用friend运算符重载应该为你的技巧并且是定义二元运算符的常用方法,只需添加:
Using friend operator overload should do the trick for you and is a common way to define binary operators, just add:
friend sample operator+(const sample& a, const sample& b); //in class
sample operator+(const sample& a, const sample& b) { //outside the class
return sample(a.x + b.x);
}
如果您希望它保留为会员,方案,没有颠倒),你必须让运算符 const
函数:
If you want it to remain a member, (which has downsides in some rare scenarios, and no upsides), you have to make the operator a const
function:
sample operator+(sample s) const; //in class
sample sample::operator+(const sample& b) const { //outside the class
return sample(this->x + b.x);
}
其中任何一个都允许操作符链接。您之前的 s = s + s1 + s2
失败的原因是 s + s1
会执行并返回一个临时 示例
对象。然后,它将尝试向该示例添加 s2
。但是暂时只能使用 const
引用 [1] ,因此只能使用 const
成员函数。由于运算符+
成员函数不是 const
函数,因此不能在 const
临时。注意,为了使它 const
,我不得不重写它,因为你的版本修改了 +
。
Either of these will allow operator chaining. The reason your previous s = s + s1 + s2
was failing, is that the s + s1
would execute and return a temporary sample
object. Then, it would attempt to add s2
to that sample. However, temporaries can only be const
references[1], and as such, can only use const
member functions. Since your operator+
member function is not a const
function, you cannot use that function on the const
temporary. Note that to make it const
, I had to rewrite it, since your version modifies the object on the left side of the +
.
[1]与异常不是特别相关,即rvalues
这篇关于对于两个或多于两个对象的C ++中的重载赋值运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!