C++:尝试将 fstream 作为参数传递时删除了函数?

Posted

技术标签:

【中文标题】C++:尝试将 fstream 作为参数传递时删除了函数?【英文标题】:C++: Deleted function when trying to pass fstream as argument? 【发布时间】:2016-06-21 17:53:23 【问题描述】:

我不知道我的代码有什么问题。我试图从控制台获取两个文件的文件路径,然后我用这些文件初始化一些 fstream 对象,一个是ios::in | ios::out,另一个是ios::binary

这是我的代码的重要部分:

// Function prototypes
void INPUT_DATA(fstream);
void INPUT_TARGETS(fstream);

int main()

    // Ask the user to specify file paths
    string dataFilePath;
    string targetsFilePath;
    cout << "Please enter the file paths for the storage files:" << endl
        << "Data File: "; 
    getline(cin, dataFilePath); // Uses getline() to allow file paths with spaces
    cout << "Targets File: "; 
    getline(cin, targetsFilePath);

    // Open the data file
    fstream dataFile;
    dataFile.open(dataFilePath, ios::in | ios::out | ios::binary);

    // Open the targets file
    fstream targetsFile;
    targetsFile.open(targetsFilePath, ios::in | ios::out);

    // Input division data into a binary file, passing the proper fstream object        
    INPUT_DATA(dataFile);

    // Input search targets into a text file
    INPUT_TARGETS(targetsFile);

    ...


// Reads division names, quarters, and corresponding sales data, and writes them to a binary file
void INPUT_DATA(fstream dataFile)

    cout << "Enter division name: ";
    ... 
    dataFile << divisionName << endl;
    ...


// Reads division names and quarters to search for, and writes them to a file
void INPUT_TARGETS(fstream targetsFile)

    cout << "\nPlease input the search targets (or \"exit\"):";
    ...
    targetsFile.write( ... );
    ...

但是,Visual Studio 在 INPUT_DATA(dataFile);INPUT_TARGETS(targetsFile); 部分对我大喊:

function "std::basic_fstream<_Elem, _Traits>::basic_fstream(const std::basic_fstream<_Elem, _Traits>::_Myt &) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 1244 of "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\fstream") cannot be referenced -- it is a deleted function

我翻遍了头文件,直到找到第 1244 行:

basic_fstream(const _Myt&) = delete;

我不知道为什么会这样。我对 C++ 还是很陌生,我可能刚刚做了一些愚蠢的事情,但是有人可以帮忙吗?

编辑:澄清标题

【问题讨论】:

【参考方案1】:

您无法复制std::fstream,因此复制构造函数被删除,正如您通过挖掘发现的那样:)

也没有理由复制std::fstream。在您的情况下,您想通过引用传递它,因为您想修改原始的std::fstream,即您在main 中创建的那个,而不是创建一个全新的(这就是复制构造函数被删除的原因,顺便说一句@ 987654325@)。

【讨论】:

最重要的是,将函数更改为采用std::istream&amp; 允许它们处理的不仅仅是文件。例如,能够通过传入字符串流来测试它们的逻辑。【参考方案2】:

那是因为std::fstream 的复制构造函数被删除了。你不能按值传递它。 要解决此问题,请通过引用传递std::fstream,如下所示:

void INPUT_DATA(fstream& dataFile)  /* ... */ 
void INPUT_TARGETS(fstream& targetsFile)  /* ... */ 

您无需更改代码中的任何其他内容。

【讨论】:

以上是关于C++:尝试将 fstream 作为参数传递时删除了函数?的主要内容,如果未能解决你的问题,请参考以下文章

C++,fstream 对象作为引用传递给函数,常量?

将 glUniform 函数作为参数传递 (C++)

使用 SWIG 时如何将 int 数组和 List<string> 作为参数从 C# 传递给 C++

从 C++ 调用 python 函数时如何将 C++ 类作为参数传递?

将指针分配给指针(并将指针传递给类)时使用删除的 C++ 混淆

c++ - 如何将void函数作为参数传递?