C++ 序列化 serialization 如何将类持久化?

本文介绍了C++如何实现类的序列化,通过保存和加载对象的二进制形式达到持久化效果。文章展示了如何为配置类添加Save和Load方法,利用fstream以二进制方式写入和读取对象的成员变量,从而实现对象的持久化存储和恢复。
摘要由CSDN通过智能技术生成

C++的类的持久化可以通过下面文章中所使用的方法来实现

其原理是将对象的内容以二进制的形式保存到文件中,

在要读取的时候再使用相反的过程来加载到对象中.

总结起来就是可以为要进行持久化的对象,比如说配置类,添加如下的两个方法:

bool Config::Save()
{
 ofstream ofs("config.bin", ios::binary);
 ofs.write((char *)this, sizeof(*this));
 return true;
}

bool Config::Load()
{
 ifstream ifs("config.bin", ios::binary); 
 ifs.read((char *)this, sizeof(*this));
 return true;
}

参考文章:

Introduction

The C++ language provides a somewhat limited support for file processing. This is probably based on the time it was conceived and put to use. Many languages that were developed after C++, such as (Object) Pascal and Java provide a better support, probably because their libraries were implemented as the demand was made obvious. Based on this, C++ supports saving only values of primitive types such as short, int, char double. This can be done by using either the C FILE structure or C++' own fstream class.

Binary Serialization

Object serialization consists of saving the values that are part of an object, mostly the value gotten from declaring a variable of a class. AT the current standard, C++ doesn't inherently support object serialization. To perform this type of operation, you can use a technique known as binary serialization.

When you decide to save a value to a medium, the fstream class provides the option to save the value in binary format. This consists of saving each byte to the medium by aligning bytes in a contiguous manner, the same way the variables are stored in binary numbers.

To indicate that you want to save a value as binary, when declaring the ofstream variable, specify the ios option as binary. Here is an example:

#include <fstream>

 

#include <iostream>

 

using namespace std;

 

 

 

class Student

 

{

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值