Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand function ostream& operator<< (ostream& os, const unsigned char* s)

Tags:

c++

For function declaration like

ostream& operator<< (ostream& os, const unsigned char* s);

I am wondering what has been returned. The CPP reference says it returns ostream object. But why it is ostream& instead of simple ostream?

Thank you

like image 297
Bin Zhou Avatar asked Jun 20 '13 14:06

Bin Zhou


1 Answers

The reason that the operator returns a ostream& (i.e. a modifiable reference to an ostream object), rather than a copy or void is that it allows for chaining, for instance, a common example with std::cout as the ostream object:

unsigned int i = 2;
std::cout << "This is a test to print " << "some text and maybe some numbers: " << i << std::endl;

Here we chain two const char*s, an unsigned int and a stream modifer, without having to seperate them with separate lines, this makes it nicer to read and understand.

like image 169
Thomas Russell Avatar answered Sep 30 '22 21:09

Thomas Russell