"C + +" in C + + overloaded output operator, why to return a reference

Source: Internet
Author: User

For: Ostream & operator << (ostream & OS, const ClassType &object)

Description: 1. The first parameter is a reference to the Ostream object, and the output is generated on that object, Ostream is non-const, because writing to the stream alters the state of the stream; The parameter is a reference because the Ostream object cannot be copied (in C + + The standard input and output stream classes defined in IStream and Ostream, where the copy constructor and assignment operator functions are placed in the private section and are only declared, not defined.
2. The second parameter should generally be a reference to the class type to be output, which is a reference to avoid copying the arguments, reducing the copy, and it is set to const because the output will not normally change the object, and the const object can be used to output both const and non-const objects. 3. The return type is a ostream reference, and its value is usually the Ostream object operated by the output operator, first because the Ostream object cannot be copied, so it must be a reference, the second reference can be copied less once, improve efficiency, and finally, in order to demonstrate continuity, to achieve continuous output, The effect of manipulating a Ostream object with multiple output operators, if not a reference, generates a new temporary object when the program returns, that is, the successive two << operators are actually for different objects, which is like cout<<a<< b; the difference from cout<<a;cout<<b;. PS: Overloaded assignment operator, continuous assignment can not return reference overloaded addition operator, continuous addition cannot return reference

"C + +" in C + + overloaded output operator, why to return a reference

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.