gpt4 book ai didi

C++几种对象序列化

转载 作者:行者123 更新时间:2023-11-30 00:38:06 25 4
gpt4 key购买 nike

所以我对单个对象进行了序列化,但我对多个对象都遇到了问题。这是代码:

    #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;
}

问题是我不知道如何在二进制文件中写入两个或多个对象,然后如何读取它们。有人知道吗?

提前致谢。

最佳答案

我建议您使用 Boost - Serialization 在 C++ 中序列化对象:http://www.boost.org/libs/serialization/

关于C++几种对象序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11712238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com