如何<<操作员工作正常? [英] How does the << Operator exactly work?

查看:95
本文介绍了如何<<操作员工作正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解<<

I have some problems in understanding the << operator.

如果我有:

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

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

现在函数运算符<<叫做。

Now the function operator<< is called.

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


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

字符串指针指向具有值 引用( cout ?)并且是ostream&

the string-pointer points to the address with value test is: but to what does the element out refer (to cout?)? and is the function body of ostream& correct in that way?

推荐答案

首先,我们修复你的代码:运算符应该使用 const 引用或值,而不是指针:

First, let's fix your code: the operators should be taking const references or values instead of pointers:

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

是正确的, out 参数接收对 cout 的引用,或者 ostream& ; << 左侧的表达式返回。尽管 - < 左侧的表达式不一定是 cout << 运算符 * 用于链接和流操纵器。在所有情况下,这些表达式返回对 ostream 的引用,以便chain可以继续。

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 <<. The expression on the left of << is not necessarily cout, though - other common cases are results of other << operators* for chaining, and stream manipulators. In all cases these expressions return a reference to ostream so that the "chain" could continue.

* 运算符<< 返回 ostream& 的原因是可以链接输出。在绝大多数情况下,您会返回与接收作为第一个参数相同的 ostream& ,但是对标准C ++库要求您做的部分没有限制

* The reason the operator<< return an ostream& is so that you could chain the output. 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.

这篇关于如何&lt;&lt;操作员工作正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆