#include <iostream>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class MyClass
{
public:
// 静态成员变量
static int staticData;
// 序列化静态数据到文件
static void SerializeStaticData(const std::string& filename)
{
std::ofstream file(filename);
boost::archive::text_oarchive oa(file);
oa << staticData;
}
// 从文件中反序列化静态数据
static void DeserializeStaticData(const std::string& filename)
{
std::ifstream file(filename);
boost::archive::text_iarchive ia(file);
ia >> staticData;
}
};
// 初始化静态成员变量
int MyClass::staticData = 0;
int main()
{
// 设置静态数据
MyClass::staticData = 42;
// 序列化静态数据到文件
MyClass::SerializeStaticData("static_data.txt");
// 清除静态数据
MyClass::staticData = 0;
// 从文件中反序列化静态数据
MyClass::DeserializeStaticData("static_data.txt");
// 打
std::cout<<MyClass::staticData<<std::endl
}
静态+非静态
#include <iostream>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class MyClass
{
public:
MyClass() = default;
MyClass(int nonStaticValue)
: nonStaticValue(nonStaticValue){}
int nonStaticValue; // 非静态成员
static int staticValue; // 静态成员
// 非静态成员的序列化函数
template <typename Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar & nonStaticValue;
}
// 静态成员的手动保存和加载函数
static void SaveStaticData()
{
std::ofstream file("static_data.txt");
boost::archive::text_oarchive oa(file);
oa << staticValue;
}
static void LoadStaticData()
{
std::ifstream file("static_data.txt");
boost::archive::text_iarchive ia(file);
ia >> staticValue;
}
};
int MyClass::staticValue = 0;
int main()
{
// 创建一个 MyClass 对象
MyClass obj(42);
// 序列化非静态成员到文件
{
std::ofstream file("object_data.txt");
boost::archive::text_oarchive oa(file);
oa << obj;
}
// 手动保存静态成员到文件
MyClass::SaveStaticData();
// 从文件中加载非静态成员
MyClass loadedObj;
{
std::ifstream file("object_data.txt");
boost::archive::text_iarchive ia(file);
ia >> loadedObj;
}
// 手动加载静态成员
MyClass::LoadStaticData();
// 打印加载后的对象和静态成员的值
std::cout << "Loaded Object: nonStaticValue=" << loadedObj.nonStaticValue << ", staticValue=" << MyClass::staticValue << std::endl;
return 0;
}