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

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

    You have to use a free function and not a member function as for binary operators the left hand side is always *this for member functions with the right hand side being passed as the other parameter.

    For output stream operators the left hand side is always the stream object so if you are streaming to a standard class and not writing the stream yourself you have to provide a free function and not a member of your class.

    Although it would be possible to provide a backwards stream operator as a member function and stream out like this:

    myObject >> std::cout;
    

    not only would you violate a very strong library convention, as you point out, chaining output operations would not work due to the left-to-right grouping of >>.

    Edit: As others have noted, while you have to make it a free function it only needs to be a friend if the streaming function cannot be implemented in terms of the class' public interface.

提交回复
热议问题