串行化



#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
using namespace std;


struct TaxInfo;

struct SalaryInfo {
 string name;
 float salary;
 TaxInfo * tax;

 void save(ostream & out);
 void load(istream & in);


//重构serialize函数

 template<class Archive>
 void serialize(Archive & ar, unsigned int version);

};


struct TaxInfo {
 float taxRate;
 TaxInfo(float taxRate=0.2): taxRate(taxRate) {
 }

 void save(ostream & out) {
  out<<"The tax rate is "<<taxRate<<endl;
 }

 void load(istream & in) {
  cout<<"Please input tax rate: ";
  cin>>taxRate;
 }

//重构serialize函数

 template<class Archive>
 void serialize(Archive & ar, unsigned int version) {
  ar & taxRate;
 }
};


void SalaryInfo::save(ostream & out) {
 out<<salary<<' ';
 out<<(tax!=0)<<endl;
 if(tax) tax->save(out);
 out<<name<<endl;
}

void SalaryInfo::load(istream & in) {
 bool f;
 in>>salary>>f;
 if(f) {
  if(!tax) tax=new TaxInfo();
  tax->load(in);
 }
 else {
  delete tax;
  tax=0;
 }
 getline(in, name);
}

template<class Archive>
void SalaryInfo::serialize(Archive & ar, unsigned int version) {
 ar & name & salary &tax;
};


int main() {

//串行化


 TaxInfo tax(0.003);
 SalaryInfo s1={ "梁涯飞雨", 500, &tax };

//创建文件输出流
 ofstream ofs("e:/salary.txt", ios_base::out);

//建立用于保存的串行化文档
 boost::archive::text_oarchive oa(ofs);

//将s1对象串行化并保存
 oa<<s1;

//串行化输出后, 要关闭文件输出流
 ofs.close();


//反串行化


 SalaryInfo s2;

//创建文件输入流
 ifstream ifs("e:/salary.txt", ios_base::in);

//奖励用于读取的串行化文档对象
 boost::archive::text_iarchive ia(ifs);

//读取串行化的SalaryInfo类型对象, 将其恢复为s2
 ia>>s2;
 ifs.close();

 cout<<s2.tax->taxRate<<endl;
 cout<<s2.name<<endl;


 system("pause");
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值