所以我对单个对象进行了序列化,但我遇到了几个问题。这是代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class MyTest
{
private:
string test;
public:
MyTest():test(""){};
void setTest(const string& test) {this->test = test;};
string getTest() const {return this->test;};
};
void writeToFile(const MyTest& m)
{
ofstream ofs("data.mbp", ios::app|ios::binary);
ofs.clear();
ofs.write((char *)&m, sizeof(m));
ofs.flush();
ofs.close();
return;
};
MyTest& readTest(MyTest& m,int num)
{
ifstream ifs;
ifs.open("data.mbp", ios::in|ios::binary);
for ( int i = 1 ; i <= num ; i++)
ifs.read((char *)&m, sizeof(m));
return m;
}
int main(int argc,char* argv[])
{
MyTest m,t;
m.setTest("Hello");
writeToFile(m);
t.setTest("World");
writeToFile(t);
t = readTest(t,1);
cout << t.getTest() << endl;
m = readTest(m,2);
cout << m.getTest() << endl;
return 0;
}
问题是我不知道如何在二进制文件中写入两个或更多对象,然后我如何读取它们。有人知道吗?
提前致谢。