C++对 对象的文件读写
一段代码:#include <iostream>
#include <cstdio>
#include <fstream>
using namespace std;
class lei{
string name;
int id;
public:
lei(){}
lei(string name, int id): name(name), id(id){}
void show(){
cout << id << ',' << name << endl;
}
lei& operator=(const lei& e){
if(this==&e)
return *this;
id = e.id;
name = e.name;
return *this;
}
friend
ostream& operator <<(ostream& o, const lei& e) {
o << e.id << ',' << e.name << endl;
}
};
int main()
{
lei l("haha", 1);
lei a;
FILE* fp = fopen("infor.txt", "a");
fwrite(&l, sizeof(lei), 1, fp);
fclose(fp);
fp = fopen("infor.txt", "r");
fread(&a, sizeof(lei), 1, fp); // 可能这个地方有问题,内存访问的错误吧! 请大神们详细的讲解一下,能否这样操作
fclose(fp);
cout << a;
}