C++ “ofstream”作为函数参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9658720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:08:22  来源:igfitidea点击:

"ofstream" as function argument

c++functionofstream

提问by Shibli

Is there a way to pass output stream as argument like

有没有办法将输出流作为参数传递

void foo (std::ofstream dumFile) {}

void foo (std::ofstream dumFile) {}

I tried that but it gave

我试过了,但它给了

error : class "std::basic_ofstream<char, std::char_traits<char>>" has no suitable copy constructor

error : class "std::basic_ofstream<char, std::char_traits<char>>" has no suitable copy constructor

回答by Boris Strandjev

Of course there is. Just use reference. Like that:

当然有。只用参考。像那样:

void foo (std::ofstream& dumFile) {}

Otherwise the copy constructor will be invoked, but there is no such defined for the class ofstream.

否则将调用复制构造函数,但没有为 class 定义这样的构造函数ofstream

回答by Joel Falcou

You have to pass a reference to the ostreamobject as it has no copy constructor:

您必须传递对该ostream对象的引用,因为它没有复制构造函数:

void foo (std::ostream& dumFile) {}

回答by Mankarse

If you are using a C++11 conformant compiler and standard library, it should be ok to use

如果您使用的是符合 C++11 的编译器和标准库,则应该可以使用

void foo(std::ofstream dumFile) {}

as long as it is called with an rvalue. (Such calls will look like foo(std::ofstream("dummy.txt")), or foo(std::move(someFileStream))).

只要它是用右值调用的。(这样的调用看起来像foo(std::ofstream("dummy.txt")), 或foo(std::move(someFileStream)))。

Otherwise, change the parameter to be passed by reference, and avoid the need to copy/move the argument:

否则,更改为通过引用传递的参数,并避免需要复制/移动参数:

void foo(std::ofstream& dumFile) {}