linux

Linux中C++如何进行序列化

小樊
41
2025-12-30 15:51:02
栏目: 编程语言

在Linux环境下,C++可以通过多种方式实现序列化。以下是一些常用的方法:

1. 使用Boost.Serialization

Boost.Serialization是一个功能强大的库,可以用来序列化和反序列化C++对象。

安装Boost.Serialization

sudo apt-get install libboost-serialization-dev

示例代码

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

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

    template<class Archive>
    void serialize(Archive &ar, const unsigned int version) {
        ar & name;
        ar & age;
    }
};

int main() {
    Person p1 = {"Alice", 30};
    std::ofstream ofs("person.txt");
    boost::archive::text_oarchive oa(ofs);
    oa << p1;
    ofs.close();

    Person p2;
    std::ifstream ifs("person.txt");
    boost::archive::text_iarchive ia(ifs);
    ia >> p2;
    ifs.close();

    std::cout << "Name: " << p2.name << ", Age: " << p2.age << std::endl;

    return 0;
}

2. 使用Cereal

Cereal是一个轻量级的C++序列化库,易于使用且性能良好。

安装Cereal

sudo apt-get install libcereal-dev

示例代码

#include <cereal/archives/json.hpp>
#include <cereal/types/string.hpp>
#include <fstream>
#include <iostream>
#include <string>

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

    template<class Archive>
    void serialize(Archive &archive) {
        archive(name, age);
    }
};

int main() {
    Person p1 = {"Bob", 25};
    std::ofstream ofs("person.json");
    cereal::JSONOutputArchive oarchive(ofs);
    oarchive(cereal::make_nvp("Person", p1));
    ofs.close();

    Person p2;
    std::ifstream ifs("person.json");
    cereal::JSONInputArchive iarchive(ifs);
    iarchive(cereal::make_nvp("Person", p2));
    ifs.close();

    std::cout << "Name: " << p2.name << ", Age: " << p2.age << std::endl;

    return 0;
}

3. 使用标准库的std::ofstreamstd::ifstream

虽然这种方法不如Boost.Serialization和Cereal强大,但对于简单的序列化需求已经足够。

示例代码

#include <fstream>
#include <iostream>
#include <string>

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

    void serialize(const std::string& filename) const {
        std::ofstream ofs(filename);
        ofs << name << " " << age << std::endl;
        ofs.close();
    }

    void deserialize(const std::string& filename) {
        std::ifstream ifs(filename);
        ifs >> name >> age;
        ifs.close();
    }
};

int main() {
    Person p1 = {"Charlie", 35};
    p1.serialize("person.txt");

    Person p2;
    p2.deserialize("person.txt");

    std::cout << "Name: " << p2.name << ", Age: " << p2.age << std::endl;

    return 0;
}

总结

选择哪种方法取决于你的具体需求和项目复杂度。

0
看了该问题的人还看了