在C++中返回 IO 对象的目的是什么?

What is the purpose of returning an IO object in C++?

本文关键字:是什么 对象 IO C++ 返回      更新时间:2023-10-16

我试图通过阅读教科书和做练习题之类的东西来自学C++,我目前正在学习的主题对我来说有点混乱,我希望得到一些澄清。我已经在网上寻找我的问题的明确答案,但还没有找到任何东西。

我目前正在学习标准库中 IO 类的详细信息,我现在所在的部分提供了一些示例,这些示例具有传递和返回 IO 对象的函数。

例如:

istream &get_value(istream &input)
{
int value;
input >> value;
return input;
}
int main()
{
get_value(cin);
return 0;
}

我从高层次上理解这里正在发生的事情。get_value函数具有对输入对象类型的引用,并且它还接受对输入对象的引用,在我的示例中,我经常使用该对象cin该对象。我知道这个函数正在控制台中读取用户的输入,并将该输入存储为value

我不明白的是返回输入对象的原因是什么。为什么这个函数不应该有一个类型void我正在使用的输入对象可以用于什么?我知道我现在没有使用它做任何事情,但它可以用来做什么?

返回值是这样您就可以在流运算符<<>>之间"链接"调用。运算符重载是这种"链接"的良好动机。

using namespace std;
class book {
string title;
string author;
public:
book(string t, string a) : title(t), author(a) { }
friend ostream &operator<<(ostream &os, const book &x);
}
ostream &operator<<(ostream &os, const book &x)
{
os << x.title << " by " << x.author << "n";
return os;
}
int main()
{
book b1 { "Around the World in 80 Days", "Jules Verne" };
book b2 { "The C Programming Language", "Dennis Ritchie" };
cout << b1 << b2; // chaining of operator<<
}

如果 operator<<没有返回 ostream,我们将无法将修改后的 ostream 从第一个运算符传递到第二个运算符<<。相反,我们必须写

cout << b1;
cout << b2;

这同样适用于输入操作,就像在您的情况下一样,带有>>

再次使用它来存储存储在缓冲区中的另一个 var。喜欢get_value(get_value(cin,v1),v2);

#include<iostream>
std::istream &get_value(std::istream &input,int& value)
{
input >> value;
return input;
}
int main()
{
int v1{}, v2 {};
std::cout<<"Enter two succesive integers: ";
get_value(get_value(std::cin,v1),v2);
std::cout<<"nThe two input integers are "<<v1<<" and "<<v2;
return 0;
}

您可以使用它来获取另一个输入值;例如:

input >> value >> value2;
相关文章: