In C , overloaded operators can be implemented either as friend functions or member functions. When it comes to the stream insertion operator "<<," certain considerations guide the choice between these approaches.
friend ostream & operator<<(ostream & os, const Paragraph& p) { return os << p.to_str(); }
This approach is commonly used for stream operators because:
ostream & operator<<(Paragraph const& rhs);
While it's tempting to think that member functions should be used for all class methods, this approach is not recommended for the "<<" operator for several reasons:
Consider the following class:
class Paragraph { std::string m_para; public: Paragraph(std::string const& init) : m_para(init) {} std::string const& to_str() const { return m_para; } };
In this case, using a friend function for the "<<" operator is the preferred choice because:
The above is the detailed content of Friend Function vs. Member Function for Operator Overloading: When is a Friend Function Preferred for `. For more information, please follow other related articles on the PHP Chinese website!