c++ - 运算符重载+添加多个对象

标签 c++ class overloading operator-keyword

我需要使用运算符重载添加多个对象,如下所示:

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/

相关文章:

c++ - 访问使用接口(interface)实例化的类的私有(private)成员

java - 方法重载

python - OpenCV 找不到正确的 CUDA 版本

c++ - 字距调整文本居中

c++ - 如何检查链表是否为空

java - 如何检查对象类别

list - Haskell - 如何计算嵌套列表中的元素

ruby - 在 Ruby 中使用重载括号 [] 访问变量

android - 在 C 代码中访问 Android 属性

c++ - 如何确保一次只有一个进程访问共享内存