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