1

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

我需要从其他方法调用此方法。我在将参数传递给方法时遇到问题。

图书馆.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);
};

图书馆.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;

我想我在引用方面有点混乱。

4

1 回答 1

7

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

改变这个:

std::ifstream books_list = fn_var;

对此:

std::ifstream &books_list = fn_var;

或者,从一开始就简单地去掉多余的局部变量。无需为输入参数声明局部引用变量,您所做的一切都是为了创建额外的别名,而这些别名并没有真正带来任何好处。的参数与read_file()的参数相同,create_books_database()因此只需按原样传递即可:

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);
} 
于 2018-03-11T17:07:17.237 回答