“ofstream” as function argument

£可爱£侵袭症+ 提交于 2019-11-27 05:39:09

问题


Is there a way to pass output stream as argument like

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


回答1:


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.




回答2:


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

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



回答3:


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

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))).

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

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


来源:https://stackoverflow.com/questions/9658720/ofstream-as-function-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!