C++中序列化需手动实现或用第三方库,1. 手动通过read/write成员函数处理二进制数据;2. Boost.Serialization支持多种格式且易用;3. JSON库如nlohmann便于跨平台交互;注意指针、字节序和版本兼容性,Boost适合通用场景,JSON适用于配置与网络传输。

在C++中,对象的序列化与反序列化没有像Java或Python那样的内置支持,需要手动实现或借助第三方库。序列化是将对象的状态转换为可存储或传输的格式(如二进制、JSON、XML),反序列化则是从该格式恢复对象。
适用于简单类,通过自定义读写函数将成员变量保存到文件或内存。
// 示例:Person类的手动序列化class Person {
public:
std::string name;
int age;
// 序列化到二进制文件
void save(std::ofstream& out) const {
size_t len = name.size();
out.write(reinterpret_cast
out.write(name.c_str(), len);
out.write(reinterpret_cast
}
// 从二进制文件反序列化
void load(std::ifstream& in) {
size_t len;
in.read(reinterpret_cast
name.resize(len);
in.read(&name[0], len);
in.read(reinterpret_cast
}
};
使用方式:
std::ofstream out("data.bin", std::ios::binary);
Person p{"Alice", 25};
p.save(out);
out.close();
std::ifstream in("data.bin", std::ios::binary);
Person p2;
p2.load(in);
in.close();
Boost提供了强大的序列化库,支持二进制、文本、XML等多种格式。
立即学习“C++免费学习笔记(深入)”;
// 需要包含头文件并链接Boost.Serialization
#include <boost/serialization/string.hpp>
#include <boost/serialization/access.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
class Person {
public:
std::string name;
int age;
Person() = default;
Person(const std::string& n, int a) : name(n), age(a) {}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & name;
ar & age;
}
};
序列化示例:
// 写入文件
std::ofstream ofs("person.txt");
boost::archive::text_oarchive oa(ofs);
Person p("Bob", 30);
oa << p;
ofs.close();
// 读取对象
std::ifstream ifs("person.txt");
boost::archive::text_iarchive ia(ifs);
Person p2;
ia >> p2;
ifs.close();
适合需要可读性或跨平台交互的场景。
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// 添加to_json和from_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; // 自动序列化
std::string s = j.dump(); // 转为字符串
// 反序列化
json j2 = json::parse(s);
Person p2 = j2;
- 成员指针或动态资源需特别处理(深拷贝、智能指针等)
- 基本类型对齐和字节序在跨平台时可能影响二进制序列化
- 版本兼容性:对象结构变化时,考虑版本字段
- Boost方法最通用,JSON适合配置或网络传输
以上就是c++++怎么把对象序列化_对象序列化与反序列化方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号