Home > Backend Development > C++ > Friend or Member Function: When Should `operator

Friend or Member Function: When Should `operator

DDD
Release: 2024-12-08 04:45:11
Original
1057 people have browsed it

Friend or Member Function: When Should `operator

When to Implement Operator<< as a Friend or Member Function

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?

Member Function vs. Friend Function

Member Function

ostream& operator<<(ostream &os, const obj& rhs);
Copy after login

Advantages:

  • Direct access to the class's private members
  • Encapsulation of streaming logic within the class

Friend Function

friend ostream &operator<<(ostream &os, const obj& rhs);
Copy after login

Advantages:

  • Can be used by multiple classes
  • Can facilitate automatic type conversion for both operands

Rationale for Decision

Equality Operators

For equality operators (e.g., ==, !=), member functions are preferred because:

  • They have direct access to the class's private data.
  • They enforce the class's internal representation for equality comparisons.

Stream Operators

For stream operators (<<, >>), friend functions are necessary:

  • They operate on objects of different types (e.g., ostream and the custom class).
  • They return a reference to the stream object for chained operations.

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template