0

I'm writing a class for complex numbers and I used operator overloading for +operator and <<operator

I noticed that when I try to print:

Complex z1(5);
Complex z2(0,1);
Complex z6 = z1+z2;
cout<<z6;

It works fine. But when I try:

Complex z1(5);
Complex z2(0,1);
cout<<(z1+z2);

I get an error:

error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'Complex')|

Why is this happaning? why cout<<1+3; is legal but cout<<z1+z2; is not ?

Here is my decleration of the operator overloading:

    friend std::ostream& operator<<(std::ostream& out, Complex& z);
    Complex operator+(const Complex& z) const;

And the implementation:

Complex Complex::operator+(const Complex& z) const{

    Complex addition;
    addition.imaginary = this->imaginary + z.imaginary;
    addition.real = this->real + z.real;
    return addition;
}


ostream& operator<<(ostream& out, Complex& z) {
    if(z.real!=0){
        if (z.imaginary>0 && z.imaginary !=1)
            out<<z.real<<" + "<<z.imaginary<<"i"<<endl;
        else if(z.imaginary ==1 )
            out<<z.real<<" + "<<"i"<<endl;
        else if(z.imaginary == 0)
            out<<z.real<<endl;
        else if (z.imaginary == -1)
            out<<z.real<<" - "<<"i"<<endl;
        else
            out<<z.real<<" - "<<abs(z.imaginary)<<"i"<<endl;
        }
    else{
        if(z.imaginary==0)
            out<<z.imaginary<<endl;
        else if (z.imaginary ==1)
            out<<"i"<<endl;
        else if (z.imaginary == -1)
            out<<"-i"<<endl;
        else
            out<<z.imaginary<<"i"<<endl;
        }
    return out;
}

Any explanation would be highly appriciated. Thanks in advance.

0 Answers0