【问题标题】:"ofstream" as function argument“ofstream”作为函数参数
【发布时间】: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

【问题讨论】:

    标签: c++ function ofstream


    【解决方案1】:

    当然有。只是使用参考。 像这样:

    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并且不能改变它的地址,或者它不能写入它?
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果你使用的是符合 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 是错误的)。
      猜你喜欢
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      相关资源
      最近更新 更多