Home >Backend Development >C++ >Should `operator

Should `operator

DDD
DDDOriginal
2024-12-17 21:42:22611browse

Should `operator

"Operator<<: Friend or Member Function? Considering the Type of Operation"

The selection between implementing operator<< as a friend or member function hinges on the type of operation being performed.

For comparison operators (==, !=, etc.), it's advisable to treat them as member functions within the class. As the class is inherently a friend of itself, it can effortlessly access and compare private members of its instances. Additionally, enabling auto conversion for one operand through free-standing functions might lead to unintended consequences; hence, the preference for member functions.

Conversely, when dealing with stream operators (<<, >>), they demand external functions as they necessitate access to a stream object outside the class's control. These functions can be either friends of the class or utilize a public method that handles streaming.

It's customary for stream operators to return references to stream objects, enabling seamless chaining of operations. Here's an example demonstrating this approach:

#include <iostream>

class Paragraph {
public:
    Paragraph(std::string const& init)
        : m_para(init)
    {}

    std::string const& to_str() const
    {
        return m_para;
    }

    bool operator==(Paragraph const& rhs) const
    {
        return m_para == rhs.m_para;
    }
    bool operator!=(Paragraph const& rhs) const
    {
        return !(this->operator==(rhs));
    }
    bool operator<(Paragraph const& rhs) const
    {
        return m_para < rhs.m_para;
    }

private:
    friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);
    std::string m_para;
};

std::ostream & operator<<(std::ostream &os, const Paragraph& p)
{
    return os << p.to_str();
}

int main()
{
    Paragraph p("Plop");
    Paragraph q(p);

    std::cout << p << std::endl << (p == q) << std::endl;
}

By understanding the nature of each operation and adhering to appropriate implementation choices, you can effectively leverage the operator<< to manipulate objects as desired.

The above is the detailed content of Should `operator. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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