简体   繁体   English

运算符和返回类型是什么意思?

[英]what does the the operator& return type mean?

So from my knowledge,所以据我所知,

istream& operator >> (istream &in, int &n);

is the declaration for how >> works (or to overload it in some way)是关于 >> 如何工作的声明(或以某种方式重载它)

But I'm confused on this "function's" return type, "istream&".但是我对这个“函数的”返回类型“istream&”感到困惑。

If I do something like cin >> x;如果我做类似 cin >> x; that means I'm putting in the reference to x, but I don't understand the return type istream &, and the parameter "in".这意味着我正在引用 x,但我不理解返回类型 istream & 和参数“in”。

What would this function look like defined?这个 function 看起来像什么定义的? what IS "in"?什么是“在”? And what is it actually RETURNING?它实际上返回的是什么? Because cin >> x does really do anything but take in an input so why does it have to return anything?因为 cin >> x 除了接受输入之外确实做了任何事情,那么为什么它必须返回任何东西呢?

Thanks!谢谢!

The standard implementation of operator >> would return a reference to the istream &in parameter which means it returns the exact same object.运算符 >> 的标准实现将返回对 istream &in 参数的引用,这意味着它返回完全相同的 object。

This is for convenience so you can write code like: cin >> x >> y;这是为了方便起见,您可以编写如下代码: cin >> x >> y;

The compiler will take what is on the left side of the operator and put in the first parameter and the right in the second .编译器将取运算符左侧内容并将第一个参数放入第二个参数中。 cin >> x >> y will translate into operator>>( (operator>>(cin, x), y ); cin >> x >> y 将转换为operator>>( (operator>>(cin, x), y );

This will first add x to the stream and use the return, the stream itself, and write y to that.这将首先将 x 添加到 stream 并使用返回值,即 stream 本身,然后将 y 写入其中。

It means it's a pass-thru in this particualar case (and many others).这意味着在这种特殊情况(以及许多其他情况)中它是一种传递 It's a contract to return something sensible with the input given.根据给定的输入返回一些合理的东西是一个合同。 Returning is is the sensible thing since it makes constructs like:返回is是明智之举,因为它会生成如下结构:

stream >> variableA >> variableB >> variableC

possible.可能的。 That's because stream >> variableA returns stream an so do the other operations.那是因为stream >> variableA返回stream其他操作也是如此。

If the function,如果 function,

istream& operator >> (istream &in, int &n);

returned, instead,相反,返回,

istream operator >>....

Then, things get complicated.然后,事情变得复杂起来。 In a worst-case scenario, every invocation of >> would copy the stream object and return the copy, which would then be copied and stored in the caller's stack, followed by calls to destructors of all those things that were copied, special circumstances excepted.在最坏的情况下,每次调用>>都会复制 stream object 并返回副本,然后将其复制并存储在调用者的堆栈中,然后调用所有被复制内容的析构函数,特殊情况除外.

By returning a reference, we can do things like chaining:通过返回一个引用,我们可以做一些事情,比如链接:

a << b << "Yo!" << c << "Wassup?" << endl;

...without all of that nonsense. ...没有所有这些废话。

& means "reference," which is essentially a pointer with stronger compile-time checking and nicer syntax. &表示“引用”,它本质上是一个具有更强编译时检查和更好语法的指针。

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

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