C++中实现序列化需手动完成,常用方法包括自定义读写函数、使用Boost.Serialization库或JSON库。自定义方法高效但繁琐;Boost支持复杂类型和多种格式,适合大型项目;JSON便于跨平台交互,推荐nlohmann/json库。选择依据性能、可读性和项目规模权衡。

在C++中实现对象的序列化与反序列化(即对象持久化)没有像Java或C#那样的内置机制,因此需要开发者手动实现。常见的做法是将对象的状态转换为字节流、文本或JSON格式,以便存储到文件或通过网络传输,之后再还原为原始对象。以下是几种常用且实用的方法。
对于简单的类,可以直接在类中定义序列化和反序列化的成员函数。
例如,有一个表示学生信息的类:
class Student {
public:
std::string name;
int age;
float score;
// 序列化:将对象写入输出流
void serialize(std::ostream& out) const {
size_t name_len = name.size();
out.write(reinterpret_cast<const char*>(&name_len), sizeof(name_len));
out.write(name.c_str(), name_len);
out.write(reinterpret_cast<const char*>(&age), sizeof(age));
out.write(reinterpret_cast<const char*>(&score), sizeof(score));
}
// 反序列化:从输入流恢复对象
void deserialize(std::istream& in) {
size_t name_len;
in.read(reinterpret_cast<char*>(&name_len), sizeof(name_len));
name.resize(name_len);
in.read(&name[0], name_len);
in.read(reinterpret_cast<char*>(&age), sizeof(age));
in.read(reinterpret_cast<char*>(&score), sizeof(score));
}
};
使用时可以配合文件流操作:
立即学习“C++免费学习笔记(深入)”;
Student s{"Alice", 20, 95.5f};
// 写入文件(序列化)
std::ofstream ofs("student.dat", std::ios::binary);
s.serialize(ofs);
ofs.close();
// 读取文件(反序列化)
Student s2;
std::ifstream ifs("student.dat", std::ios::binary);
s2.deserialize(ifs);
ifs.close();
这种方法控制力强,效率高,但需要手动处理每个字段,尤其是复杂类型时容易出错。
Boost提供了一套成熟的序列化框架,支持文本、二进制和XML格式。
首先包含头文件并声明序列化接口:
#include <boost/serialization/string.hpp>
#include <boost/serialization/access.hpp>
class Student {
public:
std::string name;
int age;
float score;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & name;
ar & age;
ar & score;
}
};
然后使用档案(archive)进行读写:
// 序列化到二进制文件
{
std::ofstream ofs("student.bin", std::ios::binary);
boost::archive::binary_oarchive oa(ofs);
Student s{"Bob", 21, 88.0f};
oa << s;
}
// 反序列化
{
std::ifstream ifs("student.bin", std::ios::binary);
boost::archive::binary_iarchive ia(ifs);
Student s;
ia >> s;
}
Boost.Serialization支持继承、指针、STL容器等复杂结构,是工业级项目中的常见选择。
对于需要可读性和跨平台交互的场景,JSON是一种理想格式。推荐使用nlohmann/json库。
示例:
#include <nlohmann/json.hpp>
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Student, name, age, score)
// 序列化为JSON字符串
Student s{"Charlie", 19, 92.0f};
nlohmann::json j = s;
std::string json_str = j.dump();
// 反序列化
nlohmann::json j2 = nlohmann::json::parse(json_str);
Student s2 = j2.get<Student>();
这种方式便于调试、日志记录和前后端数据交换,适合现代C++项目。
序列化过程中有几个关键点需要注意:
基本上就这些。根据项目需求选择合适的方式:追求性能用自定义二进制,追求通用性用JSON,大型项目推荐Boost。不复杂但容易忽略细节。
以上就是C++如何序列化和反序列化一个对象_C++对象持久化与序列化方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号