我正在将一些对象复制到文件中,它们都来自同一个类。但是我想在加载它们后调用它们的函数以执行该类应该执行的操作,以下是我目前所做的:
#include <iostream>
#include <fstream>
using namespace std;
struct a
{
virtual void print()
{
cout << "this is a.\n";
};
};
struct b : public a
{
virtual void print()
{
cout << "this is b.\n";
}
};
int main()
{
ofstream testofile("test.bin",ios::binary);
a* tempa = new a;
a* tempb = new b;
testofile.write((char*)tempa,sizeof(a));
testofile.write((char*)tempb,sizeof(b));
testofile.flush();
testofile.close();
ifstream testifile("test.bin",ios::binary);
a* x = (a*)new char[max(sizeof(a),sizeof(b))];
testifile.read((char*)x,sizeof(a));
x->print();
testifile.read((char*)x,sizeof(b));
x->print();
}
我的示例代码运行良好,但如果我注释掉保存部分并运行程序,则似乎新运行的应用程序的虚函数表无效(尽管我的代码没有改变)。问题在于我的文件管理器类不知道可能从我的基对象派生的所有可能对象,并且我想使用仅调用一次文件管理器来重建所有应用程序结构。当然,我的每个对象都有自己的保存/加载函数,但是文件管理器应该如何猜测适用于当前数据块的加载函数的位置?