why the 3c 3c operator is friend

Solutions on MaxInterview for why the 3c 3c operator is friend by the best coders in the world

showing results for - "why the 3c 3c operator is friend"
Joshua
30 Nov 2019
1#include <iostream>
2
3class Paragraph
4{
5    public:
6        explicit Paragraph(std::string const& init)
7            :m_para(init)
8        {}
9
10        std::string const&  to_str() const
11        {
12            return m_para;
13        }
14
15        bool operator==(Paragraph const& rhs) const
16        {
17            return m_para == rhs.m_para;
18        }
19        bool operator!=(Paragraph const& rhs) const
20        {
21            // Define != operator in terms of the == operator
22            return !(this->operator==(rhs));
23        }
24        bool operator<(Paragraph const& rhs) const
25        {
26            return  m_para < rhs.m_para;
27        }
28    private:
29        friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);
30        std::string     m_para;
31};
32
33std::ostream & operator<<(std::ostream &os, const Paragraph& p)
34{
35    return os << p.to_str();
36}
37
38
39int main()
40{
41    Paragraph   p("Plop");
42    Paragraph   q(p);
43
44    std::cout << p << std::endl << (p == q) << std::endl;
45}
46