I want to dump some derived class into file, then dump it back.
here the the class definition:
// base.h
#include <string>
class Base {
public:
virtual std::string show_string() = 0;
int b;
};
class A : public Base {
public:
std::string show_string() override { return "this is A"; }
int a;
};
the dumper code is:
#include <bits/stdc++.h>
#include "./base.h"
using namespace std;
int main() {
std::fstream f;
f.open("a.bin", std::ios::out);
for (int i = 0; i < 10; ++i) {
A a;
a.a = i;
a.b = i - 1;
f.write((char*)&a, sizeof(a));
}
f.close();
}
the loader code is:
#include <bits/stdc++.h>
#include "./base.h"
using namespace std;
int main() {
std::fstream f;
f.open("a.bin", std::ios::in);
char buff[65536];
f.write(buff, sizeof(buff));
A* a = (A*)buff;
cout << a->show_string() << endl;
f.close();
}
the loader crashed, I think the problem happened because there is a virtual pointer in A, which lost the address when it is loaded back.
so, how can i make it correct?
Aucun commentaire:
Enregistrer un commentaire