Why friend function is preferred to member function for operator<<

前端 未结 4 811
独厮守ぢ
独厮守ぢ 2021-02-10 06:38

When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ?

class A {

public:
void operator<         


        
4条回答
  •  你的背包
    2021-02-10 07:14

    You have no choice -- it has to be a free function.

    Note, however, that it need not necessarily be a friend function. It only needs to be a friend if you actually need to grant it private access. For example, I use the following in programming competitions:

    template 
    std::ostream& operator<<(std::ostream& os, const std::pair& p)
    {
      return os << '(' << p.first << ", " << p.second << ')';
    }
    

    No need for it to be friend, as first and second are accessible publicly.

提交回复
热议问题