Salve sto realizzando un programma in cui si vuole realizzare una classe libro. Tra le varie funzioni richieste per implementare tale classe si vuole realizzare l'overloading dell'operatore >> per leggere i dati di un libro da file binario, ma purtroppo a video ottengo solo una serie di numeri...qualcuno mi può aiutare? Un grazie per chi mi darà una mano.
Questo è il codice che stavo scrivendo
codice:#ifndef LIBRO_H_ #define LIBRO_H_ #include <fstream> #include <iostream> using namespace std; class libro{ private: char* autore; char* titolo; int anno; public: libro(const char* a="",const char* t="",const int aa=0) {autore=new char[strlen(a)+1];strcpy(autore,a);titolo=new char[strlen(t)+1];strcpy(titolo,t);anno=aa;} libro(const libro &); const libro & operator=(const libro &); const char* get_autore()const {return autore;} const char* get_titolo()const {return titolo;} int get_anno()const {return anno;} friend ofstream& operator<<(ofstream&,const libro &); friend ifstream& operator>>(ifstream&,libro &); friend ostream& operator<<(ostream&,const libro &); }; #endif #include "libro.h" libro::libro(const libro & L) { autore=new char[strlen(L.autore)+1]; strcpy(this->autore,L.autore); titolo=new char[strlen(L.titolo)+1]; strcpy(this->titolo,L.titolo); anno=L.anno; } ofstream& operator<<(ofstream& ofs,const libro & L) { ofs.write((const char*)(L.autore),strlen(L.autore)); ofs.write((const char*)(L.titolo),strlen(L.titolo)); ofs.write(reinterpret_cast<const char*>(&L.anno),sizeof(int)); return ofs; } ifstream& operator>>(ifstream& ifs,libro & L) { ifs.read((char*)(L.autore),strlen(L.autore)); ifs.read((char*)(L.titolo),strlen(L.titolo)); ifs.read(reinterpret_cast<char*>(&L.anno),sizeof(int)); return ifs; } ostream& operator<<(ostream& os,const libro & L) { os<<L.autore<<"\n"<<L.titolo<<"\n"<<L.anno<<"\n"; return os; } #include <cstdlib> #include <iostream> #include "libro.h" using namespace std; int main(int argc, char *argv[]) { libro l; ifstream in("in.dat"); if(!in) cerr<<"File inesistente\n"; else{ in>>l; cout<<l; in.close();}

Rispondi quotando