#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
class Person {
private:
friend class boost::serialization::access;
std::string name;
int age;
// 序列化函数
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & name;
ar & age;
}
public:
Person() : name(""), age(0) {}
Person(std::string n, int a) : name(n), age(a) {}
void display() const {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
void save(const std::string& filename, const Person& person) {
std::ofstream ofs(filename);
boost::archive::text_oarchive oa(ofs);
oa << person;
}
void load(const std::string& filename, Person& person) {
std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);
ia >> person;
}
int main() {
// 创建一个Person对象
Person p1("Alice", 30);
// 保存对象到文件
save("person.txt", p1);
// 从文件加载对象
Person p2;
load("person.txt", p2);
// 显示加载后的对象信息
p2.display();
return 0;
}
包含头文件:
#include <boost/archive/text_oarchive.hpp> 和 #include <boost/archive/text_iarchive.hpp>:用于文本格式的序列化和反序列化。#include <boost/serialization/string.hpp> 和 #include <boost/serialization/vector.hpp>:用于支持字符串和向量类型的序列化。类定义:
Person 类包含两个私有成员变量 name 和 age,并使用 friend class boost::serialization::access; 来允许 Boost 序列化库访问这些私有成员。serialize 函数是模板函数,用于定义如何将类的成员变量序列化和反序列化。保存和加载函数:
save 函数将 Person 对象保存到文件中。load 函数从文件中加载 Person 对象。主函数:
Person 对象 p1 并将其保存到文件 person.txt 中。p2,并显示其内容。上一篇:c++ cstring
下一篇:c++ ascii
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站