std::ifstream,删除函数的使用

std::ifstream, use of deleted function

我正在尝试编写一个从 .txt 文件中获取数据的方法。

我需要从其他方法调用这个方法。我有问题 将参数传递给方法。

Library.h:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>

class Library
{
   std::vector<std::string> &mBooks;
   std::string books_list;
   std::string output;
   std::string books_path;

   void read_file(std::string &fn, std::ifstream &fn_var, std::string 
        &s, std::vector<std::string> &vn);
   void create_books_database(std::string &fn, std::ifstream,&fn_var,
        std::string &s, std::vector<std::string> &vn);
};

Library.cpp:

void Library::read_file(std::string &fn, std::ifstream &fn_var, 
std::string &s, std::vector<std::string> &vn)
{ 
    std::string &filename = fn;
    std::ifstream &name = fn_var;
    std::string &output = s;
    std::vector<std::string> &vector_name = vn;

    name.open(filename);

    if(!name)
    {
        std::cerr<<"Failed to open file "<<filename<<std::endl;
        exit(1);
    }

    while(!name.eof())
    {
        std::getline(name, output);
        vector_name.push_back(output);
    }
}

void Library::create_books_database(std::string &fn, std::ifstream 
  &fn_var, std::string &s, std::vector<std::string> &vn)
{
    std::string books_path = fn;
    std::ifstream books_list = fn_var;
    std::string output = s;
    std::vector<std::string> mBooks = vn;

    read_file(books_path, books_list, output, mBooks);
}

错误:

src/Library.cpp: In member function ‘void                     
Library::create_books_database(std::__cxx11::string&, std::ifstream&, 
std::__cxx11::string&, std::vector<std::__cxx11::basic_string<char> 
>&)’:
src/Library.cpp:35:32: error: use of deleted function 
‘std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const 
std::basic_ifstream<_CharT, _Traits>&) [with _CharT = char; _Traits = 
std::char_traits<char>]’
 std::ifstream books_list = fn_var;

我觉得我在引用方面有点乱。

create_books_database() 中的 books_list 变量未声明为引用。您正在用一个 std::ifstream 对象初始化另一个对象,但是 std::ifstream 有一个已删除的复制构造函数,因此无法复制它。这就是错误消息所说的内容。

改变这个:

std::ifstream books_list = fn_var;

为此:

std::ifstream &books_list = fn_var;

或者,简单地删除多余的局部变量。无需为输入参数声明局部引用变量,您所做的只是创建额外的别名,而这些别名并没有真正带来任何好处。 read_file() 的参数与 create_books_database() 的参数相同,所以只需传递它们 as-is:

void Library::create_books_database(std::string &fn, std::ifstream &fn_var, std::string &s, std::vector<std::string> &vn)
{
    read_file(fn, fn_var, s, vn);
}