C++ 中两个/两个以上对象的重载加法赋值运算符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11161541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Overloaded Addition assignment operator in C++ for two /more than two objects?
提问by Raulp
I have overloaded the + operator like this
我已经像这样重载了 + 运算符
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;
}
Is this correct?
My question is If I want to add two different sample objects how will I overloaded the opeartor; e.g for s = s1 + s2;
这样对吗?我的问题是如果我想添加两个不同的示例对象,我将如何重载操作员;例如对于s = s1 + s2;
I feel like doing s = s + s1 + s2with the existing implementation.
我想s = s + s1 + s2使用现有的实现。
回答by higuaro
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);
}
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 constfunction:
如果您希望它保持成员身份(这在一些罕见的情况下有缺点,并且没有优点),则必须使运算符成为一个const函数:
sample operator+(sample s) const; //in class
sample sample::operator+(const sample& b) const { //outside the class
return sample(this->x + b.x);
}
Either of these will allow operator chaining. The reason your previous s = s + s1 + s2was failing, is that the s + s1would execute and return a temporarysampleobject. Then, it would attempt to add s2to that sample. However, temporaries can only be constreferences[1], and as such, can only use constmember functions. Since your operator+member function is not a constfunction, you cannot use that function on the consttemporary. Note that to make it const, I had to rewrite it, since your version modifies the object on the left side of the +.
其中任何一个都将允许操作符链接。您之前s = s + s1 + s2失败的原因是s + s1将执行并返回一个临时sample对象。然后,它会尝试添加s2到该样本中。但是,临时变量只能是const引用[1],因此只能使用const成员函数。由于您的operator+成员函数不是const函数,因此您不能在const临时函数上使用该函数。请注意,要做到这一点const,我必须重写它,因为您的版本修改了+.
[1]with exceptions aren't particularly relevant here, namely rvalues
[1] 例外在这里并不是特别相关,即右值

