Linux中C++如何进行序列化
导读:在Linux环境下,C++可以通过多种方式实现序列化。以下是一些常用的方法: 1. 使用Boost.Serialization Boost.Serialization是一个功能强大的库,可以用来序列化和反序列化C++对象。 安装Boost....
在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::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;
}
总结
- Boost.Serialization:功能强大,支持多种序列化格式,但依赖较多。
- Cereal:轻量级,易于使用,性能良好,支持多种序列化格式。
- 标准库:简单易用,适用于简单的序列化需求。
选择哪种方法取决于你的具体需求和项目复杂度。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Linux中C++如何进行序列化
本文地址: https://pptw.com/jishu/784929.html
