When to pass and return a function reference in C ++

I first made a complex class in C ++ that had two data members - real and imaginary. (forms a + ib). when I tried to overload the <<operator for a complex class object as follows:

friend ostream operator<<(ostream ,complex );  in .h file

ostream operator <<(ostream o,complex c){

    o<<"real part"<<c.real;
    o<<"imaginary part<<c.imaginary;
    return o;

}  

in the .cpp file, it does not work and rather opens the ios_base file and shows an error there. but the same code overloads <<excellent when I follow the link and return the link as follows -

ostream& operator <<(ostream& o,complex& c)
{



      //same as before
};

I don’t understand how the transfer and return by link helps?

+4
source share
2 answers

std :: ostream type is not a copy type. You cannot make a copy o, so you must get it by reference and return it by reference.

+8

: , , ; , .

. , , . , / , , , .

+2

All Articles