I am learning c++ on my own. I was studying operator overloading, i was able to understand addition and subtraction operator overloading. But overloading of I/O operators is a bit confusing. I have created a class for Complex numbers, now i am overloading operators.
Function prototype from Complex.h
friend ostream& operator<<(ostream&, const Complex&);
Function from Complex.cpp
ostream& operator<<(ostream& os, const Complex& value){
os << "(" << value.r <<", "
<< value.i << ")" ;
return os;
}
For friend ostream& operator<<(ostream&,const Complex&);
:
Because you declare a free function here, and would like it to access the internals (private/protected) of your Complex
objects. It is very common to have "friend free functions" for those overloads, but certainly not mandatory.
Because streams are non copyable (it does not make sense, see also this post), passing by value would require a copy. Passing Complex
by value would also require a useless copy.
Because those output operators are not supposed to modify the objects they are working on (Input operators are, obviously), so add const
to ensure that.