【发布时间】:2019-09-21 17:56:22
【问题描述】:
我正在尝试创建自定义类 A 的对象向量:
class A {
std::ifstream _file;
std::string _fileName;
public:
A(std::string &fileName) : _fileName(fileName) {
this->_file = std::ifstream(this->_fileName, std::ios::in);
}
~A() {
this->_file.close();
}
};
我主要是用一个 for 循环迭代文件名向量的 A 类的 n 个对象。
例子:
#include <iostream>
#include <string>
#include <vector>
#include "A.hpp"
int main() {
std::vector<A> AList;
std::vector<std::string> fileList = { "file1", "file2", "file3" };
for (auto &f : fileList) {
std::cout << f << std::endl;
A tempObj(f);
AList.emplace_back(tempObj);
}
return 0;
}
但我收到此错误:
/usr/include/c++/9.1.0/bits/stl_construct.h:75:7: error: use of deleted function ‘A::A(const A&)’
如果我没记错的话,因为我的类 A 中有一个成员 std::ifstream,所以复制构造函数被删除(参考:https://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream)
我该如何解决?我做错了什么?
感谢您的帮助
【问题讨论】:
-
您的代码由于其他原因无法编译。一个是你在
filesList上调用emplace_back(fileList的拼写错误),而你应该在AList上调用它。您需要给我们一个完全重现问题的最小示例。 -
谢谢。为了重现错误,我添加了更多正确的代码。
标签: c++ c++11 vector copy-constructor ifstream