C++:尝试将 fstream 作为参数传递时删除了函数?
C++: Deleted function when trying to pass fstream as argument?
我不知道我的代码出了什么问题。我正在尝试从控制台获取两个文件的文件路径,然后我用这些文件初始化一些 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.0VCincludefstream") cannot be referenced -- it is a deleted function
我在头文件中翻找了一遍,直到找到第 1244 行:
basic_fstream(const _Myt&) = delete;
我不知道为什么会这样。我对C++还很陌生,我可能刚刚做了一些愚蠢的事情,但有人可以帮忙吗?
编辑:澄清标题
你不能复制std::fstream
,所以复制构造函数被删除了,正如你通过挖掘发现的那样:)
也没有理由复制std::fstream
.在您的情况下,您希望通过引用传递它,因为您想修改原始std::fstream
,您在main
中创建的那个,而不是创建一个全新的(这就是删除复制构造函数的原因,顺便说一句:)
)。
那是因为std::fstream
的复制构造函数被删除了。不能按值传递它。 要解决此问题,请通过引用传递std::fstream
,如下所示:
void INPUT_DATA(fstream& dataFile) { /* ... */ }
void INPUT_TARGETS(fstream& targetsFile) { /* ... */ }
您不必更改代码中的其他任何内容。
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- Qt5 - 如何将"QList<T> *"指针作为信号参数传递,并在完成后将其删除?
- C++:尝试将 fstream 作为参数传递时删除了函数?
- 如何删除在 c++ 中作为构造函数参数传递的已分配变量