0

Complex.h

class Complex
    {
    public:
        Complex(int real, int imaginary);

        Complex operator+(const Complex& other);

    public:
        int real, imaginary;
    };

Complex.cpp

#include "Complex.h"

    Complex::Complex(int real, int imaginary)
    {
        this->real = real;
        this->imaginary = imaginary;
    }

    Complex Complex::operator+(const Complex& other){
        return Complex(this->real + other.real, this->imaginary + other.imaginary);
    }

Main.cpp

#include "Complex.h"
#include <iostream>

int main(){
    Complex complex1(10, 1), complex2(100, 2), complex3(1000, 3), complex(0, 0);

    // complex = complex1 + complex2 + complex3;        Not working
    complex = complex1 + complex2;                   // Working

    std::cout << complex.real << " + i (" << complex.imaginary << ")\n";

    return 0;
}

I am able to add two no's at a time but when i try to add more than 2 it shows error. I thought it should automatically process it like var1 + var2 + var3 = var1 + (sum of var2 and var3) as plus operator is right left associative (Sorry don't know if written opposite new to cpp)

jugal Shah
  • 21
  • 3
  • It worked fine [Online link](https://godbolt.org/z/3s5eWETo7). Please provide the error msg. Not working is not very helpful. – Ch3steR Feb 02 '22 at 16:54
  • Your mistake is defining `Complex::operator+` to declare **only one** of the two operands `const`. I'm sure that your error message (not shown) is also telling you that. – Drew Dormann Feb 02 '22 at 17:06
  • @DrewDormann can you elaborate a little please. operand means arguement? there's only one arguement as secong is itself object right. – jugal Shah Feb 02 '22 at 17:08
  • 1
    @jugalShah See the duplicate link. your `complex1 + complex2` is written such that `complex2` is bound to a `const` and `complex1` is not. Only one `const`. Look at the declaration and count the `const`s. – Drew Dormann Feb 02 '22 at 17:15

0 Answers0