2016-08-12 1 views
-5

Я выполняю домашнее задание на Шаблонах и читаю из файлов. У меня есть класс шаблона под названием «Cfile» и класс «Студент». Я помещу соответствующий код здесь, то спросите об ошибке:C++: невозможно преобразовать из 'std :: ifstream' в 'char *'

#include<iostream> 
#include<fstream> 
using namespace std; 

template <class T> 
class Cfile 
{ 
    ifstream fileIn; 

...jump down a bit 

T read() 
{ 

    return T(this->fileIn); //the error is in this line 

} 

И я получаю ошибку: cannot convert from 'std::ifstream' to 'char*' на обратной линии.

Студенческий класс конечно есть C'tor, который получает ifstream& in и создает новый Студент:

Student::Student(ifstream & in) 
{ 
in.read((char*)&age, sizeof(age)); 
} 

EDIT: Я думаю, я понимаю, что теперь это не так. У меня есть еще один класс с именем «MyString», и она имеет следующий метод чтения:

char* read(ifstream& in); 

Так что, может быть, я случайно переопределен метод чтения? Но тип возврата отличается, поэтому этого не должно произойти.

EDIT # 2: main.cpp -

#include"Cfile.h" 
#include"Student.h" 
#include"Queue.h" 
#include "C.h" 

int main() 
{ 
    ifstream i; 
    i.open("strings.txt"); 

    Cfile<Student>stuFile("strings.txt"); 

    Student a, b, c; 
    a.age = 10; 
    b.age = 20; 
    c.age = 30; 
    stuFile.write(a); 
    stuFile.write(b); 
    stuFile.write(c); 


    Student d = Student(i); 
    Student e = Student(i); 
    Student f = Student(i); 



    Cfile<char*> st; 
    Queue<char*> st1; 
    for (int i = 0;i < 10;i++) 
    { 
     st.read(st1.arr, 10); 
    } 
    i.close(); 

    return 0; 
} 

MyString.cpp -

#include "MyString.h" 



MyString::MyString() 
{ 
} 

MyString::MyString(char * st) 
{ 
    this->st = st; 
} 

char * MyString::read(ifstream& in) 
{ 

    in.read(this->st, sizeof(st)); 
    return st; 
} 

const char * MyString::getStr() 
{ 

    return this->st; 
} 


MyString::~MyString() 
{ 
} 

Student.cpp -

#include "Student.h" 



/*bool Student::operator==(Student student) 
{ 
    return this->name == student.name && 
     this->lastName == student.lastName && 
     this->age == student.age; 
}*/ 

Student::Student() 
{ 
} 

Student Student::read(ifstream& in) 
{ 
    in.read((char*)&age, sizeof(age)); 

    return *this; 
} 

void Student::write(ofstream & out) 
{ 
    out.write((char*)&age, sizeof(age)); 
} 

Student::Student(ifstream & in) 
{ 
    in.read((char*)&age, sizeof(age)); 
} 

Student::Student(Student &s) 
{ 

    this->age = s.age; 
} 

Student::Student(int age) 
{ 
    //Student s = new Student; 
    this->age = age; 
} 


Student::~Student() 
{ 
} 

Cfile.h -

#pragma once 
#include<iostream> 
#include<fstream> 
using namespace std; 

template <class T> 
class Cfile 
{ 
    ifstream fileIn; 
    ofstream fileOut; 
public: 

    Cfile() {}; 
    Cfile(char* _fileName) { 
     fileIn.open(_fileName, ios::binary); 
     fileOut.open(_fileName, ios::binary); 
    } 
    int read(T **apBuf, int aNum) 
     { 
      int count=0; 
      apBuf = new T*[aNum]; 
      for (int i = 0;i < aNum;i++) 
      { 

       *apBuf[i] = this->read(); 
       count++; 

      } 
      return count; 


    } 
    void write(T &t) 
    { 
     t.write(this->fileOut); 
    } 

    void write(T* apBuf, int aNum) { 
     for (int i = 0;i < aNum;i++) 
     { 
      write(apBuf[i]); 
     } 
    } 
    int size() 
    { 
     fileIn.seekg(0, ios::end); 
     return (fileIn.tellg()/sizeof(T)); 

    } 
    T read() 
    { 

     return T(this->fileIn); 

    } 
    ~Cfile() {}; 
}; 
+1

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

+1

Какая строка найдена ошибка? Можете ли вы опубликовать эту строку? – Matthias

+0

Я его отредактировал, если вам нужен еще один код, попросите его вместо downvoting. – ntrch

ответ

3

Я постараюсь ответить как можно лучше, учитывая качество вопроса.

Cfile<char*> st; 
    Queue<char*> st1; 
    for (int i = 0;i < 10;i++) 
    { 
     st.read(st1.arr, 10); // Error happens here 
    } 
    i.close(); 

, который в свою очередь, не может здесь

int read(T **apBuf, int aNum) 
{ 
    int count=0; 
    apBuf = new T*[aNum]; 
    for (int i = 0;i < aNum;i++) 
    { 

     *apBuf[i] = this->read(); // Error 
     count++; 

    } 
    return count; 


} 

Вы пытаетесь построить char * из-за ifstream, которая терпит неудачу, потому что те очень разные типы. Я предлагаю вам переосмыслить выделенную строку. Я также подозреваю, что вы не совсем уверены, что такое ifstream, поэтому я советую перечитать the documentation.
На стороне узла, ваш вызов new на apBuf = new T*[aNum]; не вызывает delete заранее, а это значит, у вас есть memory leak

+0

Благодарим за попытку ответить, но ваш ответ мне не очень понятен. apBuf - это массив указателей для ученика. И this-> read(); предполагается использовать метод чтения cfile, который возвращает ученика, созданного студентом c'tor, который получает файлIn в качестве параметра. Где я ошибаюсь? – ntrch

Смежные вопросы