所以我做了一個對象的序列化,但我有幾個問題。 下面是代碼:C++幾個對象序列化
#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;
}
的問題是,我不知道如何在二進制文件中寫入兩個或多個對象,之後我怎麼能閱讀。 有人知道嗎?
在此先感謝。
你做錯了第一個地方 - 'std :: string'使用動態分配的內存,並且即使在編寫時你也不能處理... :( – 2012-07-29 19:29:15
我必須承認我是一個java開發人員:) – 2012-07-29 19:30:10
您忘記了序列化數據!例如,你的'writetofile'打開一個文件,將* not *序列化的數據寫入文件,並刷新並關閉它。你寫的數據現在是無稽之談。 (如果你認爲它是合理的,那麼回答我:第一個字節包含什麼?最後一個字節包含什麼?你有* no *想法,因爲你從來沒有序列化過它!) – 2012-07-29 19:35:54