简体   繁体   English

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

[英]what does operator<< in std namespace do?

Of course following code works (it calls std::cout::operator<<): 当然下面的代码工作(它调用std :: cout :: operator <<):

cout << 1 << '1' << "1" << endl;

Happened to find there is also std::operator<<, and it seems it only works for char or char* arguments: 碰巧发现还有std :: operator <<,它似乎只适用于char或char *参数:

operator<<(cout, '1'); // ok
operator<<(cout, "1"); // ok
operator<<(cout, 1);   // error

So why do we need this operator and how to use it? 那么为什么我们需要这个运算符以及如何使用它?

Thanks. 谢谢。

operator<<(cout, '1'); // ok
operator<<(cout, "1"); // ok
operator<<(cout, 1);   // error

The first two works because they invoke non-member functions taking two arguments. 前两个是有效的,因为它们调用带有两个参数的非成员函数。 The functions which takes char and char const* as argument are defined as non-member (free) functions. charchar const*作为参数的函数定义为非成员 (自由)函数。

However, the function which takes int as argument is defined as member function, which means the third one needs to invoke a member function. 但是,将int作为参数的函数定义为成员函数,这意味着第三个函数需要调用成员函数。 If you invoke it as non-member function, then int would have to be converted into some type for which there exists a non-member function. 如果将其作为非成员函数调用,则必须将int转换为存在非成员函数的某种类型 So when this conversion is considered, it results in ambiguity because there are many possible conversions equally good. 因此,当考虑这种转换时,会导致模糊,因为有许多可能的转换同样好。

As said, this should work: 如上所述,这应该工作:

cout.operator<<(1); //should work

As to why some functions are defined as members and others as non-members, I don't know the answer. 至于为什么某些功能被定义为成员而其他功能被定义为非成员,我不知道答案。 It requires lots of study of the proposals and the decisions that led to this design of the library. 它需要对导致这种图书馆设计的提案和决策进行大量研究。

I always understood the reason for char , unsigned char and char* being defined as non-member functions outside the basic_ostream class is so it's easier to overload them. 我总是理解charunsigned charchar*被定义为basic_ostream之外的非成员函数的原因是因为它更容易重载它们。

See, all other operator<< use the char ones as building blocks. 看,所有其他operator<<使用char作为构建块。 So if you want to create an ostream specialized to a specific charT character type and / or traits trait type - you only have to specialize these operator<< functions. 因此,如果要创建专用于特定charT字符类型和/或traits特征类型的ostream ,则只需要专门化这些operator<<函数。

Had they been member functions, you'd have had to specialized the entire class (basically recreating all the class member functions). 如果它们是成员函数,您必须专门处理整个类(基本上重新创建所有类成员函数)。

I'm not sure that's the only reason, but that's how I've always seen it. 我不确定这是唯一的原因,但这就是我一直看到它的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM