首页 > 后端开发 > C++ > 正文

c++中如何序列化对象到文件_c++对象序列化方法

冰火之心
发布: 2025-10-13 18:53:01
原创
262人浏览过
C++中序列化对象需手动实现,常用方法有:1. 二进制I/O直接读写简单对象,适用于无指针的基本类型;2. 自定义读写函数处理含string等复杂成员的对象;3. 使用Boost.Serialization库支持STL容器、继承等复杂结构,推荐用于复杂场景;4. 结合nlohmann/json等库转为JSON格式,适合跨平台与可读性需求。选择依据对象复杂度与应用需求。

c++中如何序列化对象到文件_c++对象序列化方法

在C++中,序列化对象到文件没有像Java或C#那样的内置机制,需要手动实现。常用的方法包括使用 iostream 配合 read()write()、重载操作符、借助第三方库(如Boost)等。以下是几种常见且实用的C++对象序列化方法。

1. 使用二进制I/O直接写入简单对象

适用于只包含基本数据类型(如int、double、char数组)且不含指针或动态内存的类。

通过 ofstream::write()ifstream::read() 直接将对象内存块写入文件。

示例代码:

#include <fstream>
#include <iostream>

class Point {
public:
    int x, y;
    Point(int x = 0, int y = 0) : x(x), y(y) {}
};

int main() {
    Point p(3, 7);

    // 序列化
    std::ofstream out("point.dat", std::ios::binary);
    out.write(reinterpret_cast<const char*>(&p), sizeof(Point));
    out.close();

    // 反序列化
    Point p2;
    std::ifstream in("point.dat", std::ios::binary);
    in.read(reinterpret_cast<char*>(&p2), sizeof(Point));
    in.close();

    std::cout << "x: " << p2.x << ", y: " << p2.y << std::endl;
    return 0;
}
登录后复制
注意:这种方法不能用于含有指针、string、vector等复杂成员的类,否则会导致未定义行为。

2. 手动序列化复杂对象(自定义读写)

适用于包含字符串、容器或动态资源的对象。

将对象逐个字段写入文本或二进制文件,反序列化时按相同顺序读取。

立即学习C++免费学习笔记(深入)”;

示例:序列化含std::string的类

序列猴子开放平台
序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台0
查看详情 序列猴子开放平台
#include <fstream>
#include <string>

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("person.dat", std::ios::binary);
p.save(out);
out.close();

// 读取
Person p2;
std::ifstream in("person.dat", std::ios::binary);
p2.load(in);
in.close();
登录后复制

3. 使用Boost.Serialization库(推荐)

Boost提供强大且灵活的序列化支持,支持STL容器、继承、指针等复杂结构。

需安装Boost,并包含相应头文件。

示例:

#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <fstream>

class Person {
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version) {
        ar & name;
        ar & age;
    }
public:
    std::string name;
    int age;
    Person() {} // 默认构造函数必需
    Person(std::string n, int a) : name(n), age(a) {}
};

// 保存
void save() {
    Person p("Bob", 30);
    std::ofstream os("person.txt");
    boost::archive::text_oarchive oa(os);
    oa << p;
}

// 加载
void load() {
    Person p;
    std::ifstream is("person.txt");
    boost::archive::text_iarchive ia(is);
    ia >> p;
    std::cout << p.name << ", " << p.age << std::endl;
}
登录后复制
支持格式:text(可读)、binary、xml。编译时需链接Boost库。

4. 使用JSON或其他格式(现代C++常用)

结合nlohmann/json等库,将对象转为JSON字符串存储,适合配置或跨平台场景。

示例:

#include <nlohmann/json.hpp>
#include <fstream>

using json = nlohmann::json;

class Person {
public:
    std::string name;
    int age;

    // 转为JSON
    json to_json() const {
        return json{{"name", name}, {"age", age}};
    }

    // 从JSON恢复
    static Person from_json(const json& j) {
        Person p;
        p.name = j.at("name");
        p.age = j.at("age");
        return p;
    }
};

// 使用
Person p{"Charlie", 35};
json j = p.to_json();
std::ofstream o("person.json");
o << j.dump(4); // 格式化输出
登录后复制
基本上就这些。选择哪种方式取决于对象复杂度和是否需要可读性、跨平台兼容性。简单结构可用二进制IO,复杂对象推荐Boost或JSON方案。

以上就是c++++中如何序列化对象到文件_c++对象序列化方法的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号