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

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

 

{

 

public:

 

        char   FullName[40];

 

        char   CompleteAddress[120];

 

        char   Gender;

 

        double Age;

 

        bool   LivesInASingleParentHome;

 

};

 

 

 

int main()

 

{

 

        Student one;

 

 

 

        strcpy(one.FullName, "Ernestine Waller");

 

        strcpy(one.CompleteAddress, "824 Larson Drv, Silver Spring, MD 20910");

 

        one.Gender = 'F';

 

        one.Age = 16.50;

 

        one.LivesInASingleParentHome = true;

 

       

 

        ofstream ofs("fifthgrade.ros", ios::binary);

 

 

 

        return 0;

 

}

 

Writing to the Stream

The ios::binary option lets the compiler know how the value will be stored. This declaration also initiates the file. To write the values to a stream, you can call the fstream::write()method.

After calling the write() method, you can write the value of the variable to the medium. Here is an example:

#include <fstream>

 

#include <iostream>

 

using namespace std;

 

 

 

class Student

 

{

 

public:

 

        char   FullName[40];

 

        char   CompleteAddress[120];

 

        char   Gender;

 

        double Age;

 

        bool   LivesInASingleParentHome;

 

};

 

 

 

int main()

 

{

 

        Student one;

 

 

 

        strcpy(one.FullName, "Ernestine Waller");

 

        strcpy(one.CompleteAddress, "824 Larson Drv, Silver Spring, MD 20910");

 

        one.Gender = 'F';

 

        one.Age = 16.50;

 

        one.LivesInASingleParentHome = true;

 

       

 

        ofstream ofs("fifthgrade.ros", ios::binary);

 

 

 

        ofs.write((char *)&one, sizeof(one));

 

 

 

        return 0;

 

}

 

Reading From the Stream

Reading an object saved in binary format is as easy as writing it. To read the value, call the ifstream::read() method. Here is an example:

#include <fstream>

 

#include <iostream>

 

using namespace std;

 

 

 

class Student

 

{

 

public:

 

        char   FullName[40];

 

        char   CompleteAddress[120];

 

        char   Gender;

 

        double Age;

 

        bool   LivesInASingleParentHome;

 

};

 

 

 

int main()

 

{

 

/*      Student one;

 

 

 

        strcpy(one.FullName, "Ernestine Waller");

 

        strcpy(one.CompleteAddress, "824 Larson Drv, Silver Spring, MD 20910");

 

        one.Gender = 'F';

 

        one.Age = 16.50;

 

        one.LivesInASingleParentHome = true;

 

       

 

        ofstream ofs("fifthgrade.ros", ios::binary);

 

 

 

        ofs.write((char *)&one, sizeof(one));

 

*/

 

        Student two;

 

 

 

        ifstream ifs("fifthgrade.ros", ios::binary);

 

        ifs.read((char *)&two, sizeof(two));

 

 

 

        cout << "Student Information/n";

 

        cout << "Student Name: " << two.FullName << endl;

 

        cout << "Address:      " << two.CompleteAddress << endl;

 

        if( two.Gender == 'f' || two.Gender == 'F' )

 

               cout << "Gender:       Female" << endl;

 

        else if( two.Gender == 'm' || two.Gender == 'M' )

 

               cout << "Gender:       Male" << endl;

 

        else

 

               cout << "Gender:       Unknown" << endl;

 

        cout << "Age:          " << two.Age << endl;

 

        if( two.LivesInASingleParentHome == true )

 

               cout << "Lives in a single parent home" << endl;

 

        else

 

               cout << "Doesn't live in a single parent home" << endl;

 

       

 

        cout << "/n";

 

 

 

        return 0;

 

}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/268035.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

BZOJ 4808: 马(二分图最大点独立集)

http://www.lydsy.com/JudgeOnline/problem.php?id4808 题意&#xff1a; 思路&#xff1a; 这图中的两个马只能选一个&#xff0c;二选一&#xff0c;很像二分图吧&#xff0c;对能互吃的两个棋子连线&#xff0c;在所选的任意两个棋子中&#xff0c;都不能互相有连线&#x…

使用Flink批处理实现WordCount

Flink作为一个非常优秀的大数据实时计算框架&#xff0c;在很多从事大数据开发的公司都是必备的技能&#xff0c;接下来我将通过Flink以批处理来实现入门案例WordCount 1:步骤一 idea新建设maven项目&#xff0c;并且自己配置好maven环境 2&#xff1a;步骤二 在pom文件中加…

Application.DoEvents

记得第一次使用Application.DoEvents()是为了在加载大量数据时能够有一个数据加载的提示&#xff0c;不至于系统出现假死的现象&#xff0c;当时也没有深入的去研究他的原理是怎样的&#xff0c;结果在很多地方都用上了Application.DoEvents()&#xff0c;今天看到了关于这方面…

Servlet交互【重定向 与 请求分派】详解

Servlet交互 在serlvet中&#xff0c;需要调用另外一个资源来对浏览器的请求进行响应&#xff0c;两种方式实现&#xff1a; 调用HttpServletResponse.sendRedirect 方法实现 重定向 调用RequestDispatcher.forward 方法来实现请求分派 &#xff08;转发&#xff09; 1.reponse…

解决Error: No such file or directory @ rb_sysopen

mac使用brew安装flink时出现报错&#xff0c;是下载openjdk11报错的 原因是openjdk11依赖包下载不成功&#xff0c;使用brew单独下载该依赖包即可 brew install openjdk11

《Sibelius 脚本程序设计》连载(十四) - 2.1 注释、语句、语句块

《Sibelius 脚本程序设计》连载(Flash 格式) 转载于:https://www.cnblogs.com/Sibelius/archive/2010/12/11/1903389.html

Mac Brew install 报错Command failed with exit 128:git

问题&#xff1a; 记录一个问题&#xff0c;Mac使用Brew安装Flink报错 具体如图所示&#xff0c;执行brew install apache-flink Error: Command failed with exit 128: git 解决方式&#xff1a; 输入brew -v后会提示你执行两个配置命令&#xff0c;直接复制执行就ok了&am…

[转载]一个游戏程序员的学习资料

想起写这篇文章是在看侯杰先生的《深入浅出MFC》时,突然觉得自己在大学这几年关于游戏编程方面还算是有些心得&#xff0c;因此写出这篇小文,介绍我眼中的游戏程序员的书单与源代码参考。一则是作为自己今后两年学习目标的备忘录,二来没准对别人也有点参考价值。我的原则是只写…

Mac上安装flink笔记

1&#xff1a;步骤一 首先要有破jdk1.8&#xff0c;查看命令&#xff1a;java -version 2:步骤二 使用brew安装flink&#xff0c;命令如下&#xff1a; brew install apache-flink 3:步骤三 我这边安装的时候报错了&#xff0c;解决方式如下 报错1 解决方式 https://blog.…

工作笔记一——杂项

近期做的项目中遇到一些棘手的问题&#xff0c;解决的过程用到很多知识&#xff0c;在此记下主要的问题与解决方法。 页面功能介绍&#xff1a;获取五张表格的大量数据&#xff08;大概有几千条记录&#xff09;&#xff0c;然后到前台显示在table里面&#xff0c;实现行列汇总…

Coolite 中GridView行按钮取行ID并调用服务器端代码

效果图&#xff1a; 关系代码&#xff1a; <Command Handler"if(commandbutSelectReocrd){strrecord.data.SessionId; #{AjaxMethods}.SelectRecord(str);}" /> 全部html代码&#xff1a; 代码 <ext:GridPanel ID"GridPanel1"Height"325&quo…

Flink的三种执行模式STREAMING和BATCH和AUTOMATIC

执行模式 执行模式三种 BATCH模式的两种配置方法 什么时候选择BATCH模式

activemq生产者和消费者的双向通信

http://websystique.com/spring/spring-4-jms-activemq-example-with-jmslistener-enablejms/转载于:https://www.cnblogs.com/zhangshitong/p/7906468.html

大学生必犯的N大错误(1)

1&#xff09;不会英语&#xff1a; 计算机科学源于美国&#xff0c;重量级的文档都是英文的。不会英语的你只能忍受拙劣的翻译和很大延迟的文档和图书&#xff08;翻译出来的优秀的文档和图书几乎都是很久以前的出版物&#xff09;。 语言的重要性&#xff0c;实际上体现的是沟…

RabbitMQ基础概念详细介绍

转至&#xff1a;http://www.ostest.cn/archives/497 引言 你是否遇到过两个&#xff08;多个&#xff09;系统间需要通过定时任务来同步某些数据&#xff1f;你是否在为异构系统的不同进程间相互调用、通讯的问题而苦恼、挣扎&#xff1f;如果是&#xff0c;那么恭喜你&#x…

ubuntu 目录及文件权限 000 444 666 777(转)

转载自&#xff1a;http://hi.baidu.com/im886/blog/item/434764d9f6c210f838012f0b.html 1 [001] 执行权限 x2 [010] 只写权限 w4 [100] 只读权限 r sudo chmod 600 &#xff08;只有所有者有读和写的权限&#xff09; sudo chmod 644 &#xff08;所有者有读和写的权限&am…

信号与系统(中)

第四章 线性时不变系统的时域分析 4.1连续时间系统的时域分析 微分方程的求解 齐次解特解完全解起始状态到初始状态的转换 冲激平衡法连续时间系统的零输入响应与零状态响应 双零法4.2离散时间系统的时域分析 迭代法时域经典法双零法差分方程的求解 齐次解特解完全解离散时间系…

对自学还是培训的看法

在论坛上看到的帖子&#xff0c;转过来&#xff0c;标题是 “对自学还是培训的看法” http://bbs.51cto.com/thread-605267-1.html 转载于:https://blog.51cto.com/gooltsing/467392