gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:51:06 24 4
gpt4 key购买 nike

我正在尝试创建一个自定义类 A 的对象 vector :

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 循环迭代文件名 vector 推送 n 个 A 类对象。

例子:

#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:错误:使用已删除的函数‘A::A(const A&)’

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

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

谢谢你的帮助

最佳答案

正如您所说,由于 ifstream 成员,您的 A 类不可复制,该成员无法复制。所以你的类的复制构造函数默认被删除。但是当您将 tempFile 传递给 emplace_back() 时,您正试图复制构造一个 A 对象。

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

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

for (auto &f : fileList)
{
AList.emplace_back(f);
}

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

A::A(std::string &fileName)
: _file(fileName), _fileName(fileName)
{
}

关于自定义类对象的 C++ vector - 复制构造函数已删除 - std::ifstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58042770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com