核心是直接内存写入,通过write/read函数序列化POD类型;非POD需手动处理字段,如先存字符串长度再存内容,确保跨平台兼容性与资源安全。

在C++中实现二进制对象序列化,核心是将对象的内存布局直接写入文件,读取时再按相同格式还原。这种方式高效且紧凑,适合保存自定义类型或复杂数据结构。
二进制序列化依赖于 write() 和 read() 函数,它们以字节流形式操作数据。
对于POD(Plain Old Data)类型,可以直接写入内存块:
#include <fstream>
#include <iostream>
struct Point {
    int x;
    int y;
};
void savePoint(const Point& p, const std::string& filename) {
    std::ofstream file(filename, std::ios::binary);
    file.write(reinterpret_cast<const char*>(&p), sizeof(p));
    file.close();
}
void loadPoint(Point& p, const std::string& filename) {
    std::ifstream file(filename, std::ios::binary);
    file.read(reinterpret_cast<char*>(&p), sizeof(p));
    file.close();
}
类中包含指针、STL容器(如 string、vector)时,不能直接写入,因为它们指向堆内存。
立即学习“C++免费学习笔记(深入)”;
解决方案是手动序列化每个字段:
struct Person {
    std::string name;
    int age;
    void save(std::ofstream& file) const {
        // 先写字符串长度
        size_t len = name.size();
        file.write(reinterpret_cast<const char*>(&len), sizeof(len));
        // 再写字符串内容
        file.write(name.c_str(), len);
        // 写基本类型
        file.write(reinterpret_cast<const char*>(&age), sizeof(age));
    }
    void load(std::ifstream& file) {
        size_t len;
        file.read(reinterpret_cast<char*>(&len), sizeof(len));
        name.resize(len);
        file.read(&name[0], len);
        file.read(reinterpret_cast<char*>(&age), sizeof(age));
    }
};
建议将文件操作封装在函数中,利用局部对象自动析构来关闭文件,避免资源泄漏。
示例用法:
void savePerson(const Person& p, const std::string& filename) {
    std::ofstream file(filename, std::ios::binary);
    if (file) {
        p.save(file);
    }
}
void loadPerson(Person& p, const std::string& filename) {
    std::ifstream file(filename, std::ios::binary);
    if (file) {
        p.load(file);
    }
}
基本上就这些。只要注意内存布局、大小端问题(跨平台时)和非POD类型的处理,二进制序列化就能可靠工作。不复杂但容易忽略细节。
以上就是C++如何在文件I/O中实现二进制对象序列化的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号