如何理解函数ostream&operator <<(ostream&os,const unsigned char*s)

Bin*_*hou 5 c++

对于函数声明,如

ostream& operator<< (ostream& os, const unsigned char* s);
Run Code Online (Sandbox Code Playgroud)

我想知道返回了什么.CPP引用表示它返回ostream对象.但为什么它是ostream而不是简单的ostream?

谢谢

Tho*_*ell 5

操作符返回ostream&(即ostream对象的可修改引用)而不是副本或void的原因是它允许链接,例如,std::cout作为ostream对象的常见示例:

unsigned int i = 2;
std::cout << "This is a test to print " << "some text and maybe some numbers: " << i << std::endl;
Run Code Online (Sandbox Code Playgroud)

在这里,我们链接两个const char*s,an unsigned int和一个流修改器,而不必用单独的行分隔它们,这使得它更好地阅读和理解.


Ale*_*xis 1

因为你像这样返回“os”,所以你可以进行链接;

std::cout << "string1" << "string2" << std::endl;
Run Code Online (Sandbox Code Playgroud)