C++类的序列化需手动实现或借助第三方库。1. 手动实现通过重载读写函数将成员变量存入流;2. Boost.Serialization支持多种格式和复杂类型,使用归档机制自动处理;3. JSON库如nlohmann/json适用于可读和跨平台场景,通过to_json/from_json转换;4. 注意访问权限、指针处理、字节序及版本兼容性,根据需求选择合适方案。

在C++中,标准库并没有直接提供类的序列化与反序列化机制,不像Java或C#那样内置支持。因此,要实现C++类的序列化(将对象保存为字节流或文本)和反序列化(从字节流或文本恢复对象),需要手动实现或借助第三方库。以下是几种常见且实用的方法。
最基础的方式是通过重载输入输出操作符或自定义读写函数,将对象的成员变量逐个写入文件或内存缓冲区。
// 示例:简单Person类的手动序列化class Person {
private:
std::string name;
int age;
public:
Person() = default;
Person(const std::string& n, int a) : name(n), age(a) {}
// 序列化:将对象写入输出流
void serialize(std::ostream& out) const {
size_t nameLen = name.size();
out.write(reinterpret_cast
out.write(name.data(), nameLen);
out.write(reinterpret_cast
}
// 反序列化:从输入流恢复对象
void deserialize(std::istream& in) {
size_t nameLen;
in.read(reinterpret_cast
name.resize(nameLen);
in.read(&name[0], nameLen);
in.read(reinterpret_cast
}
};
使用示例:
std::ofstream out("data.bin", std::ios::binary);
Person p("Alice", 30);
p.serialize(out);
out.close();
std::ifstream in("data.bin", std::ios::binary);
Person p2;
p2.deserialize(in);
in.close();
Boost提供了功能强大且类型安全的序列化库,支持文本、二进制、XML等多种格式,并能自动处理复杂对象关系(如指针、STL容器等)。
立即学习“C++免费学习笔记(深入)”;
// 需包含头文件并链接Boost.Serialization#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class Person {
private:
std::string name;
int age;
// 序列化访问声明
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & name;
ar & age;
}
public:
Person() {}
Person(const std::string& n, int a) : name(n), age(a) {}
};
使用示例(文本归档):
std::ofstream ofs("person.txt");
boost::archive::text_oarchive oa(ofs);
Person p("Bob", 25);
oa << p; // 自动调用serialize
ofs.close();
反序列化:
std::ifstream ifs("person.txt");
boost::archive::text_iarchive ia(ifs);
Person p2;
ia >> p2;
ifs.close();
对于需要可读性和跨平台交互的场景,JSON是很好的选择。nlohmann的JSON库支持C++类的序列化。
定义转换函数:
using json = nlohmann::json;
void to_json(json& j, const Person& p) {
j = json{{"name", p.name}, {"age", p.age}};
}
void from_json(const json& j, Person& p) {
j.at("name").get_to(p.name);
j.at("age").get_to(p.age);
}
使用:
Person p = {"Charlie", 35};
json j = p; // 自动调用to_json
std::string s = j.dump(); // 转为字符串
Person p2 = s; // 或:from_json(json::parse(s), p2);
序列化时需注意以下几点:
基本上就这些。手动实现适合简单场景,Boost功能全面但引入依赖,JSON适合配置或网络传输。选择哪种方式取决于项目需求和环境限制。
以上就是C++如何实现类的序列化与反序列化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号