C++ - 当流指针作为函数参数给出时意味着什么?

Man*_*ons 0 c++ pointers iostream

我对 C++ 不太熟悉,所以很抱歉这是一个如此简单的问题。我正在做一项学校作业,在其中一个问题中,它要求我们编写一个具有以下原型的函数

    void function_name(istream &in, ostream &out, other arguments);
Run Code Online (Sandbox Code Playgroud)

我真的不知道前两个参数是什么意思。据我所知,如果我错了,请纠正我。istream 是一个在输入中使用的类。cin 是此类的一个对象。ostream 是在输出中使用的类。cout 和 cerr 是此类的对象。istream 类的对象具有fail() 和.eof() 等方法来检测输入期间的错误。ostream 类的对象具有 .width() 和 . precision() 等方法来帮助格式化输出。

因此,根据我对问题的理解,前两个参数必须是指向 istream 和 ostream 对象的指针。谁能给我一个以 istream 和 ostream 对象指针作为参数的函数示例,以便我能够理解如何在我的问题中使用它们?

抱歉,如果这太长了。谢谢您的帮助。

R S*_*ahu 5

前两个参数必须是指向 istream 和 ostream 对象的指针

这是一个误解。这些参数是引用参数,而不是指针。

例子:

void foo(istream &in, ostream &out, int& x)
{
    in >> x;
    out << x;
}

int main()
{
   int x;

   // Read x from stdin and write to stdout
   foo(std::cin, std::cout, x);

   std::ifstream ifile("input.txt");
   std::ofstream ofile("output.txt");

   // Read x from input.txt and write to output.txt
   foo(ifile, ofile, x);
}
Run Code Online (Sandbox Code Playgroud)