在Linux环境下,C++可以通过多种方式实现序列化。以下是一些常用的方法:
Boost.Serialization是一个功能强大的库,可以用来序列化和反序列化C++对象。
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;
}
Cereal是一个轻量级的C++序列化库,易于使用且性能良好。
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;
}
std::ofstream和std::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;
}
选择哪种方法取决于你的具体需求和项目复杂度。