在std命名空间中operator <<是什么做的?

use*_*598 13 c++

当然下面的代码工作(它调用std :: cout :: operator <<):

cout << 1 << '1' << "1" << endl;
Run Code Online (Sandbox Code Playgroud)

碰巧发现还有std :: operator <<,它似乎只适用于char或char*参数:

operator<<(cout, '1'); // ok
operator<<(cout, "1"); // ok
operator<<(cout, 1);   // error
Run Code Online (Sandbox Code Playgroud)

那么为什么我们需要这个运算符以及如何使用它?

谢谢.

Naw*_*waz 7

operator<<(cout, '1'); // ok
operator<<(cout, "1"); // ok
operator<<(cout, 1);   // error
Run Code Online (Sandbox Code Playgroud)

前两个是有效的,因为它们调用带有两个参数的非成员函数.这需要的功能charchar const*作为参数被定义为非成员(免费)的功能.

但是,int作为参数的函数被定义为成员函数,这意味着第三个函数需要调用成员函数.如果将其作为非成员函数调用,则int必须转换为存在非成员函数的某种类型.因此,当考虑这种转换时,会导致模糊,因为有许多可能的转换同样好.

如上所述,这应该工作:

cout.operator<<(1); //should work
Run Code Online (Sandbox Code Playgroud)

至于为什么某些功能被定义为成员而其他功能被定义为非成员,我不知道答案.它需要对导致这种图书馆设计的提案和决策进行大量研究.