自定义类对象的 C++ 向量 - 删除复制构造函数 - std::ifstream

gim*_*iki 2 c++ vector copy-constructor ifstream c++11

我正在尝试创建自定义类 A 的对象向量:

\n\n
class A {\n    std::ifstream _file;\n    std::string _fileName;\npublic:\n    A(std::string &fileName) : _fileName(fileName) {\n        this->_file = std::ifstream(this->_fileName, std::ios::in);\n    }\n    ~A() {\n        this->_file.close();\n    }\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

主要是我使用 for 循环迭代文件名向量来推送 A 类的 n 个对象。

\n\n

例子:

\n\n
#include <iostream>\n#include <string>\n#include <vector>\n#include "A.hpp"\n\nint main() {\n\n    std::vector<A> AList;\n    std::vector<std::string> fileList = { "file1", "file2", "file3" };\n\n    for (auto &f : fileList) {\n        std::cout << f << std::endl;\n        A tempObj(f);\n        AList.emplace_back(tempObj);\n    }\n\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但我收到此错误:\n/usr/include/c++/9.1.0/bits/stl_construct.h:75:7: error: use of deleted function \xe2\x80\x98A::A(const A&)\xe2\x80\x99

\n\n

如果我没记错的话,因为我的 A 类中有一个成员 std::ifstream,所以复制构造函数被删除(参考:https://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream

\n\n

我该如何解决?我做错了什么?

\n\n

感谢您的帮助

\n

Rem*_*eau 5

就像你说的,A由于成员的原因,你的班级是不可复制的ifstream,而成员是无法复制的。所以你的类的复制构造函数默认被删除。但是当您传递给 时,您试图复制构造一个A对象。tempFileemplace_back()

您需要将文件名传递给emplace_back()并让它A通过将字符串转发到构造函数来为您构造向量内的对象:

std::vector<A> AList;
std::vector<std::string> fileList;

for (auto &f : fileList)
{
    AList.emplace_back(f);
}
Run Code Online (Sandbox Code Playgroud)

附带说明一下,您的构造函数可以并且应该ifstream成员初始化列表中而不是在构造函数主体中初始化:

A::A(std::string &fileName)
    : _file(fileName), _fileName(fileName)
{
}
Run Code Online (Sandbox Code Playgroud)