Why is the stream insertion operator overloaded to a global function?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.