Q:

operator overloading as a friend

I was trying to write a Complex number class , with overloading of the operator + - * as friend like below:
ComplexNumber operator+(const ComplexNumber &c1, const ComplexNumber& c2)
{
    return ComplexNumber(c1._r+c2._r, c1._i+c2._i);
}

ostream& operator << ( ostream &out,  ComplexNumber &c){
    out << c.getReal() <<'+'
        << c.getImg()  <<'I' << std::endl; 
}

I experience no problems while doing:
ComplexNumber c1(1,2);
cout << c1 << endl;

but when I try to do the following:
ComplexNumber c2(2,1);
cout << c1 + c2 << endl;

I get an error:

no known conversion for argument 1 from ‘ComplexNumber’ to ‘ComplexNumber&’

I know the problem is that that the return value of the operator+ is a ComplexNumber, but the ostream operator needs a ComplexNumber&.
I don't know how to deal with this. Thanks

A:

I don't know why it would say argument 1, but you should make your output overload take a const reference:
ostream& operator << ( ostream &out,  const ComplexNumber &c){
                                      ^^^^^

It's better because a temporary can be used and you don't modify it.

