Home >Backend Development >C++ >Friend Function vs. Member Function for Operator
Operator<< in C : Friend Function vs. Member Function
In C , the operator<< can be defined either as a friend function or as a member function. This article explores the rationale behind choosing one over the other in specific scenarios.
Friend Function Approach for Operator<<
When defining operator<< as a friend function, the syntax typically involves the following:
friend bool operator<<(obj const& lhs, obj const& rhs);
This approach is recommended when the relationship comparison involves examining the private members of the class. Since friend functions have access to the private members of a class, they can perform the comparison directly.
Member Function Approach for Operator<<
In this approach, the operator<< is defined as a member function of the class:
ostream& operator<<(obj const& rhs);
This approach is appropriate when the comparison involves publicly accessible data or simple operations. However, it has a key limitation: if the comparison requires access to private members, the member function approach cannot be used.
Comparison of Approaches
Streaming Operations:
When defining operator<< for streaming operations, both friend functions and member functions can be used. However, friend functions must be used if the streaming operation needs to modify the stream object (e.g., adding line breaks).
Equality and Relationship Operators:
For operators such as ==, !=, <, >, and so on, it is preferred to define them as member functions. This approach allows for easy comparison of private members within the class. Additionally, it simplifies the code by avoiding the need for additional friend functions.
Example
Consider the following example of a Paragraph class with a to_str() method:
class Paragraph { public: Paragraph(std::string const& init) : m_para(init) {} std::string const& to_str() const { return m_para; } };
Friend Function Approach:
friend ostream & operator<<(ostream &os, const Paragraph& p) { return os << p.to_str(); }
Member Function Approach:
ostream & operator<<(ostream &os) { return os << paragraph; }
In this case, the friend function approach is preferred as it allows access to the private member m_para for streaming operations.
The above is the detailed content of Friend Function vs. Member Function for Operator. For more information, please follow other related articles on the PHP Chinese website!