Introduction:
Operator overloading allows us to extend operators like << to work with custom classes. The question arises: should operator<< be implemented as a friend function or a member function within the class?
ostream& operator<<(ostream &os, const obj& rhs);
Advantages:
friend ostream &operator<<(ostream &os, const obj& rhs);
Advantages:
For equality operators (e.g., ==, !=), member functions are preferred because:
For stream operators (<<, >>), friend functions are necessary:
Example:
Consider a Paragraph class with a private m_para string member. We want to implement operator<< to print the paragraph's text:
class Paragraph { public: Paragraph(const string& init) : m_para(init) {} const string& to_str() const { return m_para; } bool operator==(const Paragraph& rhs) const { return m_para == rhs.m_para; } friend ostream &operator<<(ostream &os, const Paragraph& p); private: string m_para; }; ostream &operator<<(ostream &os, const Paragraph& p) { return os << p.to_str(); }
In this example, operator<< is implemented as a friend function because it operates on different types and returns a stream reference. The to_str() method is used to access the private m_para member and convert it to a string for output.
The above is the detailed content of Friend or Member Function: When Should `operator. For more information, please follow other related articles on the PHP Chinese website!