将对std :: ifstream的引用作为参数传递 [英] Pass a reference to std::ifstream as parameter

查看:95
本文介绍了将对std :: ifstream的引用作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ifstream& 参数编写函数.

I'm trying to write a function with an ifstream& argument.

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

这给了我一个错误:

类型'ifstream'(也称为'basic_ifstream')不提供呼叫操作符.

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

你能请我怎么了吗?

推荐答案

呼叫运算符是类似于 operator()(params)的函数,允许使用语法 myObject(params).

call operator is a function like operator()( params ) allowing to use the syntax myObject( params ).

因此,当您编写 infile(...)时,您正在尝试为我们提供呼叫操作员.

So, when you write infile(...), you are trying to us a call operator.

您要执行的操作是打开文件,使用 open 方法:

What you are trying to do is to open a file, use the open method:

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

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

But, as commented, it does not really make sense to pass infile reference to such a function. You may consider:

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;
}

这篇关于将对std :: ifstream的引用作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆