2016-04-18 3 views
0

Я использую ifstream для захвата ввода из файла, как показано в моем коде ниже.Как правильно использовать ссылку ifstream в этом контексте? Ошибка C2248

Я понимаю, что вы не можете захватить ifstream напрямую, поскольку это частный член. Какова работа над тем, чтобы схватить его с помощью ссылки и как бы выглядел синтаксис?

Ниже приведены мои B.cpp и B.h, я не думаю, что прикрепление других файлов необходимо, но может при необходимости. Также я приложил сообщение об ошибке ниже этого!

Спасибо за любую помощь заранее!

B.h:

#ifndef B_H 
#define B_H 
#include <string> 
#include <fstream> 
#include <sstream> 
#include <iomanip> 
#include <algorithm> 
#include <cctype> 
#include <iostream> 

class B { 
    public: 
     //Variable declarations 
     std::string line, delimiter, token, str; 
     std::ifstream inputfile; 
     size_t pos; 
     int lineRead; 

     //Function declarations 
     B(); 
     void setValues(int lineNum); 
     std::string printValues(); 
     bool to_bool(std::string str); 
    protected: 
     float f; 
     int i; 
     bool b; 
     std::string s; 
}; 

#endif 

B.cpp:

#include "B.h" 

B::B() { 

} 

void B::setValues(int lineNum) { 
    lineRead = 0; 
    pos = 0; 
    delimiter = " "; 

    inputfile.open("file.txt"); 

    while (!inputfile.eof()) { 
     //increment line counter 
     lineRead++; 

     //read line 
     getline(inputfile,line); 

     //if this is the line requested fill the template members with the 
     //correct data. <string, int, float, bool> 
     if(lineNum == lineRead){ 
      //getting the string 
      pos = line.find(delimiter); 
      token = line.substr(0, pos); 
      str = token; 
      line.erase(0, pos + delimiter.length()); 

      //getting the integer 
      pos = line.find(delimiter); 
      token = line.substr(0, pos); 
      i = stoi(token); 
      line.erase(0, pos + delimiter.length()); 

      //getting the float 
      pos = line.find(delimiter); 
      token = line.substr(0, pos); 
      f = stof(token); 
      line.erase(0, pos + delimiter.length()); 

      //getting the boolean 
      pos = line.find(delimiter); 
      token = line.substr(0, pos); 
      b = to_bool(token); 
      line.erase(0, pos + delimiter.length()); 
     } 
    } 

    //close the file 
    inputfile.close(); 
} 

std::string B::printValues() { 
    return s + " " + std::to_string(i) + " " + std::to_string(f) + " " + std::to_string(b) + "\n"; 
} 

//Changes a string to lower case and then reads the string 
//to find if the value is true or false. Returns a boolean. 
bool to_bool(std::string str) { 
    transform(str.begin(), str.end(), str.begin(), ::tolower); 
    std::istringstream is(str); 
    bool tempB; 
    is >> std::boolalpha >> tempB; 
    return tempB; 
} 

S.h:

#ifndef S_H 
#define S_H 
#include "B.h" // required to make B known here 
#include <string> // known through B, but better safe than sorry 
class S : public B { 

public: 
    S(std::string name); 
    std::string subPrint(); // *** 
protected: 
    std::string s2; 
}; 
#endif 

S.cpp:

#include "S.h" 

S::S(std::string name) : s2(name) { 

} 

std::string S::subPrint() { 
    return s2 + " " + printValues(); 
} 

main.cpp:

#include "S.h" 
#include <vector> 

using namespace std; 

int main() { 
    int itPos = 0; 

    vector<S> v; 

    S s1("Jon"); 
    S s2("Mike"); 
    S s3("Kim"); 
    S s4("Steve"); 
    S s5("Kevin"); 

    v.push_back(s1); 
    v.push_back(s2); 
    v.push_back(s3); 
    v.push_back(s4); 
    v.push_back(s5); 

    cout << v[0].subPrint(); 

    system("pause"); 
    return 0; 
}; 

Error

+0

Какова фактическая ошибка, которую вы получаете? – NathanOliver

+0

Ошибка находится в ссылке под кодом @NathanOliver. – jon

+0

Извините, может быть, я думаю об этом неправильно, @kfsone проверить мою ошибку на изображении. – jon

ответ

1

Вы выпустить здесь в том, что std::ifstream не копируемая. Это значение B не может быть скопировано и в свою очередь S не может быть скопировано. При добавлении S «S в вектор

v.push_back(s1); 
v.push_back(s2); 
v.push_back(s3); 
v.push_back(s4); 
v.push_back(s5); 

вектор пытается копировать то, что было передано ему, чтобы поместить его в векторе.

Простым решением для этого является сброс ifstream от членов класса и только его наличие в качестве локальной переменной в setValues, поскольку это единственное место, где оно используется.

+0

я переехал его на месте в setValues ​​(), но я не получаю эту ошибку: 'Ошибка \t \t 1 ошибка LNK2019: неразрешенный внешний символ«общественности: BOOL __thiscall B :: to_bool (класс станд :: basic_string <голец, структура станд :: char_traits , класс std :: allocator >) "(? to_bool @ B @@ QAE_NV? $ basic_string @ DU? $ char_traits @ D @ std @@ V? $ allocator @ D @ 2 @@ std @@@ Z), на который ссылается функция «public: void __thiscall B :: setValues ​​(int)» (? SetValues ​​@ B @@ QAEXH @ Z) ', а также эта ошибка:« Ошибка ошибка LNK1120: 1 неразрешенная externals' – jon

+0

@jon Вы изменили параметр функции для 'setValues'? Все, что вам нужно было сделать, это удалить строку 'std :: ifstream inputfile;' из 'B', а затем изменить' inputfile.open («file.txt»); 'in' setValues' '' inputstream filefile ("file.txt «);'. – NathanOliver

+0

Да, я изменил его на 'std :: ifstream inputfile (" file.txt ");' – jon