Getting error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'Complex') despite overloading the << operator

Viewed 927

I am a newbie programmer and I am writing a simple program that adds two complex numbers. I have overloaded << in the following way:

ostream& operator << (ostream& output, Complex &complex_num){

        output << complex_num.realPart << " + " << "(" << complex_num.imaginaryPart << ")i" <<endl;
        return output;

    }

My addition function is as follows:

Complex operator +(Complex &c2){
        Complex temp;
        temp.realPart=realPart+c2.realPart;
        temp.imaginaryPart=imaginaryPart + c2.imaginaryPart;
        return temp;
    }

In my main function, when I try to print out the result by typing in :

cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num1 + num2<< endl; 

I get an error saying no match for operator <<. However, when I assign another object num3 = num1 + num2 and then write the following code, the program runs fine.

cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num3<< endl; 

What is happening here? Can anyone please help me?

1 Answers

Your operator+ returns a Complex, which is a temporary object. It doesn't work when used with the operator<<, because you are trying to bind it to a non-const reference argument.

A variable can be bound to a non-const reference, so that works.

The fix would be to take the argument to operator<< by const reference:

ostream& operator << (ostream& output, Complex const &complex_num);

so it now works for temporaries as well. Even better, it works for const arguments too.

Related