'ofstream' 和 'fstream' 正在读取文件

'ofstream' and 'fstream' reading files

fstream& fileReading(const string& signalFile, const string& backgroundFile){
    ofstream fileName;
    fileName.open(signalFile, ios::in | ios::binary);

 //does more stuff here

    return fileName;
}

我收到以下错误消息:

对类型 'fstream' 的非常量左值引用不能绑定到不相关类型 'ofstream' 的值。

我不确定这意味着什么或为什么我会收到它。

我感觉这与fstream 和ofstream 的声明有关。

当我将 return 类型更改为 ofstream 时,我收到一条消息,其中指出: 引用与局部变量关联的堆栈内存 'fileName' returned.

我想要一些帮助来理解所有这些意味着什么以及我如何将 function/method 重构为 return 我将创建和写入的文件。

如有任何帮助,我们将不胜感激。 c++ 初学者必须即时学习这门语言。

您必须 return 文件处理程序 (&fileName) 的地址而不是文件名,因此您的代码必须是:

fstream& fileReading(const string& signalFile, const string& backgroundFile){
    ofstream fileName;
    fileName.open(signalFile, ios::in | ios::binary); 
    return fileName;
}

并且您必须按如下方式调用此函数:

fstream* fileHandlerPointer = fileReading("sample.txt" , "sample2.tct");

这里有两个问题:

  • 您正在尝试 return 对本地对象的引用;该对象在范围的末尾被销毁,然后您将 return 引用它;这是无效的。考虑 return 实例,而不是引用。

  • 您正在尝试 return 与函数 return 不同的对象。考虑将函数更改为 return ofstream 实例,然后确保它是 return 通过移动编辑的:

    std::ofstream fileReading(const string& signalFile,
                               const string& backgroundFile)
    {
        return std::ofstream{ signalFile, ios::in|ios::binary };
    }