https://www.coursera.org/learn/cpp-chengxu-sheji/lecture/c3tbl/ Liu-cha-ru-yun-suan-fu-he-liu-ti-qu-yun-suan-fu-de-zhong-zai notes
Part 1. Overloads of the stream insert operator: cout<<5<<endl; Cout is overloaded with "<<" in a Ostream object iostream defined in Iosream. cout<<5; namely cout.operator<< (5); Overloaded functions for "<<" in iostream:
Ostream & ostream::operator<< (int n) { ... // Code for Output n return *this// *this is cout}
Part 2. Why the stream insert operator is overloaded to a global function is assumed to have complex object C, if you want to use cout<<c to output, it is necessary to overload the "<<". However, 1) cannot overload the "<<" in the Ostream class because the Ostream class is already encapsulated. 2) "<<" cannot be overloaded in the complex class, otherwise *this objects will be confused.
classcomplex{ Public: intA,b;};o Stream&operator<< (ostream &os, Complex &x) {//cout<<x<<endl;os<<x.a<<"+i"<<x.b; //the "os<<x.a" is os.operator<< (X.A); //and in the definition of os.operator<< (), it should returned *this//which represents a Ostream object returnOS;}
Why is the stream insertion operator overloaded to a global function?