我需要使用运算符重载添加多个对象,如下所示:
ex1 operator+(const ex1 &c1, const ex1 &c2, more++){
return ex1(c1 + c2 + more++);
}
此函数添加两个对象,但我想添加多个对象。这可能吗?
int main(){
// first for example I want to add 3 objects
ex1 ob1, ob2, ob3;
ob1 + ob2 + ob3;
code..
code..
// and after that I want to add for example 10 or more objects
ex1 ob1, ob2, ob3,..., ob10;
ob1 + ob2 + ob3 +....+ ob10;
}
最佳答案
只需定义
ex1 operator+(const ex1 &c1, const ex1 &c2){
return ex1(c1.inner_value + c2.inner_value);
}
然后
a + b + c
将被解释为
operator+( operator+(a,b) , c )
所以它应该有效
关于c++ - 运算符重载+添加多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34697208/