c++ - 传递对 std::ifstream 的引用作为参数

标签 c++ function ifstream

我正在尝试编写一个带有 ifstream& 参数的函数。

void word_transform(ifstream & infile)
{
    infile("content.txt");
    //etc
}

这给了我一个错误:

Type 'ifstream' (aka 'basic_ifstream ') does not provide a call operator.

请问有什么问题吗?

最佳答案

调用运算符 是一个类似于 operator()( params ) 的函数,允许使用语法 myObject( params )

因此,当您编写 infile(...) 时,您正在尝试向我们调用接线员。

你要做的是打开一个文件,使用open方法:

void word_transform(ifstream & infile)
{
    infile.open("content.txt",std::ios_base::in);
    if ( infile.is_open() )
        infile << "hello";
    infile.close();
}

但是,正如所评论的那样,将文件引用传递给这样的函数实际上没有任何意义。您可以考虑:

void word_transform(istream& infile)
{
    infile << "hello";
}

int main()
{
    ifstream infile;
    infile.open("content.txt",std::ios_base::in);
    if ( infile.is_open() )
        word_transform( infile );
    infile.close();
    return 0;
}

或者:

void word_transform()
{
    ifstream infile;
    infile.open("content.txt",std::ios_base::in);
    if ( infile.is_open() )
        infile << "hello";
    infile.close();
}

int main()
{
    word_transform();
    return 0;
}

关于c++ - 传递对 std::ifstream 的引用作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27501160/

相关文章:

c++ - 这是内联函数的有效用法吗?

c++ - 如何从函数中读取文件中的数据

使用自定义协议(protocol)时的 C++ 应用程序根目录

c++ - 不匹配 ‘operator+=’ aka std::_Rb_tree_const_iterator std::map

python - 将 C++ 包装到 Python - 其中部分代码是没有源代码的共享库

c++ - 为什么 gcc8.3 似乎试图编译未使用的模板函数?

c++ - 简单的 std::sort 不工作

R:如何应用为多列输出数据帧的函数(使用 dplyr)?

bash - 需要为 "While Loop"中使用的每个 Sed 替换生成新的随机数

c++ - 如何检查 '\t' ?