C++中实现对象序列化需手动操作,常见方法包括:1. 重载<<和>>或自定义save/load函数进行文本或二进制读写;2. 使用Boost.Serialization库支持多种格式及复杂类型;3. 采用JSON(如nlohmann/json)或Protobuf实现跨平台、语言通用的序列化;4. 注意指针管理、字节序、版本兼容与敏感字段处理。简单场景可手动实现,复杂项目推荐Boost或通用数据格式方案。

在C++中实现对象序列化(即把对象的状态保存为字节流,便于存储或传输)不像Java或Python那样有内置支持,需要手动实现。常见的做法是通过重载输入输出操作符、使用第三方库,或自行设计序列化机制来完成数据持久化。
对于简单的类,可以手动定义如何将对象写入文件或从文件读取。
基本思路是将对象的成员变量逐个写入文本或二进制文件。
示例:假设有一个 Person 类:
立即学习“C++免费学习笔记(深入)”;
class Person {
public:
std::string name;
int age;
// 写入文件
void save(std::ofstream& out) const {
size_t len = name.size();
out.write(reinterpret_cast<const char*>(&len), sizeof(len));
out.write(name.c_str(), len);
out.write(reinterpret_cast<const char*>(&age), sizeof(age));
}
// 从文件读取
void load(std::ifstream& in) {
size_t len;
in.read(reinterpret_cast<char*>(&len), sizeof(len));
name.resize(len);
in.read(&name[0], len);
in.read(reinterpret_cast<char*>(&age), sizeof(age));
}
};
使用方式:
Person p{"Alice", 25};
// 序列化
std::ofstream out("data.bin", std::ios::binary);
p.save(out);
out.close();
// 反序列化
std::ifstream in("data.bin", std::ios::binary);
Person p2;
p2.load(in);
in.close();
Boost 提供了强大的序列化库,支持文本、XML 和二进制格式,能自动处理复杂类型(如STL容器、继承等)。
需安装 Boost 并包含头文件。
示例:#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class Person {
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() {}
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", 30);
oa << p;
}
// 反序列化
{
std::ifstream ifs("person.txt");
boost::archive::text_iarchive ia(ifs);
Person p;
ia >> p;
}
支持 binary_oarchive、xml_oarchive 等多种格式。
若需跨语言或网络传输,推荐使用通用格式。
JSON(用 nlohmann/json):#include <nlohmann/json.hpp> NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Person, name, age) // 序列化 nlohmann::json j = p; std::string str = j.dump(); // 转字符串 // 反序列化 Person p2 = j.get<Person>();
定义 .proto 文件:
message Person {
string name = 1;
int32 age = 2;
}
编译后生成 C++ 类,使用 SerializeToString / ParseFromString 实现高效二进制序列化。
基本上就这些方法。简单项目可用手动序列化,中大型项目推荐 Boost 或 JSON/Protobuf 方案,兼顾效率与可维护性。
以上就是C++怎么实现对象序列化_C++数据持久化与对象序列化方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号