【发布时间】:2012-03-11 20:44:52
【问题描述】:
有没有办法像
一样将输出流作为参数传递void foo (std::ofstream dumFile) {}
我试过了,但它给了
error : class "std::basic_ofstream<char, std::char_traits<char>>" has no suitable copy constructor
【问题讨论】:
有没有办法像
一样将输出流作为参数传递void foo (std::ofstream dumFile) {}
我试过了,但它给了
error : class "std::basic_ofstream<char, std::char_traits<char>>" has no suitable copy constructor
【问题讨论】:
当然有。只是使用参考。 像这样:
void foo (std::ofstream& dumFile) {}
否则将调用复制构造函数,但没有为类ofstream定义。
【讨论】:
std::ostream&(注意f的缺失)。
template<typename Char, typename Traits> … std::basic_ostream<Char, Traits>&
void foo (const std::ofstream& dumFile)它会做什么,它会写信给dumFile并且不能改变它的地址,或者它不能写入它?
您必须传递对 ostream 对象的引用,因为它没有复制构造函数:
void foo (std::ostream& dumFile) {}
【讨论】:
如果你使用的是符合 C++11 的编译器和标准库,应该可以使用
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"))。请注意,gcc 的标准库还没有实现这个构造函数,而 clang 的标准库有(即上面的代码用 clang 编译但没有用 gcc;gcc 是错误的)。