为什么在传递 std::ofstream 作为参数时要"use of deleted"函数?

Why do I make "use of deleted" function when passing a std::ofstream as parameter?

本文关键字:use of 函数 deleted std ofstream 为什么 参数      更新时间:2023-10-16

我有一个成员是std::ofstream fBinaryFile和a

void setFile( std::ofstream& pBinaryFile ) 
{
    fBinaryFile = pBinaryFile;
}
输出:

 Data.h:86:16: error: use of deleted function ‘std::basic_ofstream<char>& std::basic_ofstream<char>::operator=(const
 std::basic_ofstream<char>&)’
     fBinaryFile = pBinaryFile;
                 ^

我明白std::ofstream中的副本是不允许的,也许我错过了一些东西。能否将pBinaryFile的含量保存在fBinaryfile中?

因为相关的操作符被声明为

ofstream& operator= (const ofstream&) = delete;

这意味着它是明确禁止的,所以ofstream语义确实支持复制。

根据您的体系结构,您可以存储或移动指针/引用。

如果你想复制pBinaryFile的内容到fBinaryFile,你需要将pBinaryFile声明为ifstream(输入文件流),而不是ofstream(输出文件流)它应该看起来像这样:

std::ifstream pBinaryFile;
std::ofstream fBinaryFile;
std::stringstream sstream;
std::string line
pBinaryFile.open(pBinaryFileName.c_str());
fBinaryFile.open(fBinaryFileName.c_str());
if (pBinaryFile.isopen()) {
    while (pBinaryFile.good()) {
        getline(pBinaryFile, line);
        fBinaryFile << sstream(line) << endl;
    }
}
pBinaryFile.close();
fBinaryFile.close();

注意pBinaryFileName和fBinaryFileName是指你的文件路径。

这段代码可能有错误,但我认为解决方案看起来像这样。

我建议进一步阅读:

http://www.cplusplus.com/doc/tutorial/files/