在C++中返回 IO 对象的目的是什么?
What is the purpose of returning an IO object in C++?
我试图通过阅读教科书和做练习题之类的东西来自学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;
相关文章:
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 是什么让放置新调用对象的构造函数?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 为对象分配整数.输出将是什么?
- 在C++中,创建'n'数量的对象的推荐方法是什么,其中n是用户定义的。我该怎么做?
- 使用 gtest 框架在单元测试代码中检查目标对象的私有变量的最佳实践是什么?
- 处理从列表中删除指向对象的指针的"healthy"方法是什么?
- 在C++中返回 IO 对象的目的是什么?
- 在C++中有多个指向单个对象的指针的正确方法是什么?
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 将(临时的?)std::string传递给使用它来构造一个接受副本的对象的函数的最佳方法是什么?
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 使用对函数和IO对象的引用(作为参数)的目的是什么
- 这些情况有什么区别?我怎么知道什么是临时对象?
- 在多个对象中初始化预定义成员变量的正确方法是什么?
- 在 c++ 中重置大型对象实例的最佳方法是什么
- 将对象传递给模板构造函数或方法的正确方法是什么
- 面向对象概念的例子车,这里应该是什么对象