Using friend functions for I/O operator overloading in c++
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.
You do not have to make the streaming operator a friend. It does have to be externally declared as the Complex object is on the right-hand side of the operator.
However if your Complex class has a way to access the members required (possibly through getters) you could get the streaming operator to use them. Say:
std::ostream& operator<<( std::ostream& os, Complex const& cpx )
{
return os << cpx.getReal() << ',' << cpx.getImaginary();
}
Your operator/
overload can be done as an internal function but actually is better implemented also as an external function with two const& parameters. If it is a member function it needs to be a const-member. Yours is not.
You might implement it based on operator /=
thus
Complex operator/ ( Complex const& lhs, Complex const& rhs )
{
Complex res( lhs );
res /= rhs; // or just put return in front of this line
return res;
}
1.Can anyone explain(on a basic level) that why do we have to use friend function here?
If you need to access private member of Complex
in operator<<
.
2.Why do we have to pass operator by reference?
For efficiency. Passing by const reference is faster than passing by value for user defined type usually.
3.This function works fine without using const, but why are we using const here? What is the advantage of passing Complex as a constant object?
If you don't do so, you can't output a const object, such as:
const Complex c;
std::cout << c;
链接地址: http://www.djcxy.com/p/73110.html
上一篇: 在文件路径中转义空格