简体   繁体   English

<<操作符如何工作?

[英]How does the << Operator exactly work?

I have some problems in understanding the << operator. 我在理解<<运算符时遇到一些问题。

If I have: 如果我有:

#include <iostream>
using namespace std;
//...

int t = 5;
cout << "test is: " << t << endl;

Now the function operator<< is called. 现在调用函数operator <<。

ostream& operator<<(ostream& out, string* s)
{
    return out << s << endl;
}


ostream& operator<<(ostream& out, int* value)
{
    return out << value << endl;
}

the string-pointer points to the address with value test is: but to what does the element out refer (to cout ?)? 字符串指针指向带有值test的地址是:但是out元素引用的什么( cout ?)? and is the function body of ostream& correct in that way? 并且ostream&的功能主体是否正确?

Thank you so much for any explanation. 非常感谢您的解释。

First, let's fix your code: the operators should be taking const references or values instead of pointers: 首先,让我们修复您的代码:运算符应采用const引用或值而不是指针:

ostream& operator<<(ostream& out, const string& s) // const reference
ostream& operator<<(ostream& out, int i)           // value

Now to your question: you are correct, the out parameter receives the reference to the cout , or whatever is the ostream& returned from the expression on the left side of << . 现在,您的问题是:您是对的, out参数接收对cout的引用,或者从<<左侧的表达式返回的ostream&是什么。 The expression on the left of << is not necessarily cout , though - other common cases are results of other << operators * for chaining, and stream manipulators. 尽管<<左边的表达式不一定是cout ,但是-其他常见情况是其他<<运算符*的结果,用于链接和流操纵器。 In all cases these expressions return a reference to ostream so that the "chain" could continue. 在所有情况下,这些表达式都返回对ostream的引用,以便“链”可以继续。

* The reason the operator<< return an ostream& is so that you could chain the output. * operator<<返回ostream&的原因是为了可以链接输出。 In overwhelming number of cases you wold return the same ostream& that you receive as the first parameter, although there is no limitation on the part of the standard C++ library requiring you to do that. 在绝大多数情况下,您都会返回ostream&第一个参数相同的ostream& ,尽管标准C ++库中没有要求您执行此操作的限制。

This is not true. 这不是真的。 It's int not int* , and char const* not string* . intint* ,和char const*不是string*

out , of course, refers to std::cout in this example. 在本示例中, out当然是指std::cout What else would it be? 还有什么呢?

And no those bodies are not correct in the slightest — they attempt to reinvoke themselves infinitely, and do nothing else. 而且,没有任何一个机构在任何方面都不是正确的,它们试图无限地重新唤起自己,并且什么也不做。

int t = 5;
cout << "test is: " << t << endl;

First call would be to:- 第一个电话是:

ostream& operator<<(ostream& out, const char* str)

out = cout 出=出局

str = "test is: " str =“ test is:”

Second call would be applied on object returned by first call which is ostream . 第二次调用将应用于第一次调用返回的对象ostream

ostream& operator<<(ostream& out, int x)

out = cout 出=出局

x = t

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

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