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

前端 未结 4 803
独厮守ぢ
独厮守ぢ 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:20

    You can't. But If you don't want it to be a friend function, make it a free function and implement it in terms of the class' public interface. For eg.

     ostream& operator<<(ostream& os, Myclass& obj)
    {
       return obj.print(os);
    }
    
    ostream& MyClass::print(ostream& os)
    {
       os << val; // for example.
       return os;
    }
    

提交回复
热议问题