有没有一种方法可以像这样将输出流作为参数传递:
void foo (std::ofstream dumFile) {}
我尝试了一下,但出现了以下错误:
error : class "std::basic_ofstream<char, std::char_traits<char>>"没有合适的复制构造函数
当然可以,只需要使用引用。 像这样:
void foo (std::ofstream& dumFile) {}
否则将会调用拷贝构造函数,但该类 ofstream
并未定义该函数。你必须传递一个 ostream
对象的引用,因为它没有复制构造函数:
void foo (std::ostream& dumFile) {}
void foo(std::ofstream dumFile) {}
foo(std::ofstream("dummy.txt"))
或foo(std::move(someFileStream))
。否则,请将参数更改为通过引用传递,并避免需要复制/移动参数。void foo(std::ofstream& dumFile) {}
std::ofstream
具有移动构造函数,因此可以将临时对象传递给声明为void foo(std::ofstream)
的函数,例如使用foo(std::ofstream("file"))
。请注意,尽管clang的标准库已经实现了这个构造函数(即上面的代码可以在clang中编译),但gcc的标准库尚未实现(即上述代码无法在gcc中编译;gcc是错误的)。 - Dietmar Kühl
std::ostream&
更可取(请注意没有f
)。 - Dietmar Kühltemplate<typename Char, typename Traits> … std::basic_ostream<Char, Traits>&
- Philippvoid foo (const std::ofstream& dumFile)
,它会做什么?它会向dumFile
写入内容并且无法更改其地址,还是它不能写入其中? - thedarkside ofthemoon