>>运算符的返回值

刚刚看了一篇文章,上面写着:

使用>>运算符返回运算符左侧的>>操作数。

此外,它还提供了一些示例,例如:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    int a, b, c;

    cout << "Insert 3 integers " << endl;
    cin >> a >> b >> c;
    cout << endl;
    cout << "The three integers are " << endl << a << endl << b << endl << c;

    return 0;
}

引用的句子是真的吗?我无法在我的书中或任何其他参考网站中找到此信息。

回答

>>输入流的运算符(即从 派生的类std::basic_istream)确实返回其左侧运算符。这样您就可以“链接”输入操作,就像您在cin >> a >> b >> c;语句中所做的那样。

看看它的作用,我们首先输入afromcin然后继续输入该操作b返回值cin >> a。再一次,对于第三个输入(to c)。

因此,为了清楚起见添加括号,我们得到:

( ( ( cin >> a ) >> b ) >> c );
//               ^ Here, the LH operand is the returned value of (cin >> a)

如果>>操作符没有这种行为,我们将不得不将单个语句编写为三个独立的语句,如下所示:

cin >> a; cin >> b; cin >> c;

<<运算符(输出流)的作品在一个非常类似的方式。


回答

是的,当用于std::istreams时确实如此。这个:

std::cin >> a >> b >> c;

变成这样:

std::cin.operator>>(a).operator>>(b).operator>>(c);

也就是说,cin >> a返回一个std::istream&(to std::cin),然后用于>> b返回一个std::istream&用于>> c

  • “*这……变成了……*”——并非总是如此。它也可以更像这样:`operator&gt;&gt;(operator&gt;&gt;(operator&gt;&gt;(std::cin, a), b), c)`,或`lhs.operator&gt;&gt;(rhs)的任意组合` 和 `operator&gt;&gt;(lhs, rhs)`。这实际上取决于 `a`、`b` 和 `c` 的特定类型,以及它们的运算符是否/如何重载。

以上是&gt;&gt;运算符的返回值的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>