C++的几个对象序列化
C++ several object serialization
所以我对单个对象进行了序列化,但对几个对象都有问题。这是代码:
#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/
有很多不同的方法可以做到这一点。您需要先选择一种文件格式。首先考虑XML。复杂数据结构的序列化最好基于一些现有的库,而不是自己从头开始编写。在Inet上搜索这样的库。
相关文章:
- 如何返回一个类的两个对象相加的结果
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 如何在C++中从文件中读取/写入多个对象
- 最多获取2个对象
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 无法使用VAO和EBO(openGL)绘制多个对象
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 如何复制包含指向其他几个成员之一的指针的对象?
- 在几个对象中找到一个相同的元素
- 我应该如何跟踪几个对象
- C 11按几个属性的自定义对象集合
- 几个使用相同原型的共享对象导致错误:数据库中已经存在文件
- C++的几个对象序列化
- 找出几个对象的最大尺寸以放置新
- 你能同时对一个对象调用几个方法吗
- 关于字符串对象寿命的几个问题