Why operator<< operator overload must be a friend function Why operator<< operator overload must be a friend function?

one,

If it is an overloaded binary operator (that is, a member function of a class), just set one parameter as the right-hand operand, and the left-hand operand is the object itself. . . . . .

And >> or << left operand is cin or cout rather than the object itself, so the latter point is not satisfied. . . . . . . . It can only be declared as a friend function. . .

If it must be declared as a member function, it can only be in the following form:

ostream & operator<<(ostream &output)

{

  return output;

}

So when using this << operator it becomes this form: data<<cout;

Not in line with human habits.

 

two,

cout << f1 << f2;

//Represented by overloaded operators, it can only be implemented by friends. If you want to use member functions, there will be cout.operator<<(const F& f), so this is impossible. Therefore, you can only use friends to Implementation, operator<<(cout, f) and cout is of ostream type, so it has the following standard format. Note that const cannot be added, because cout is to be changed, which will change the buffer members in it.

friend ostream& operator<<( ostream& cout, constF&) // Standard overloaded format for output operators.

friend istream& operator>>(istream& is, F& f){ } //input operator overloading standard format

class T;
T t;
If you are a member, you have to use it like this
t<<cout;
instead of
cout<<t
And it can't be chained.
cout<<t<<t<<t<<endl;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326042303&siteId=291194637