【发布时间】:2021-08-20 12:16:39
【问题描述】:
我已经成功地将我的 Employee 对象序列化为 文件格式 使用 Boost 库,我想使用 TCP/IP 通信协议通过套接字发送它,但我猜该协议不适用于文件。
我正在考虑将对象序列化和反序列化为二进制格式,但我不知道该怎么做,我在互联网上没有找到示例,请您帮帮我吗? p>
我将与您分享我的代码:
#include <fstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
using namespace std;
class Employee {
private:
friend class boost::serialization::access;
int id;
string name;
float salary;
template<class Archive>
void serialize(Archive &a, const unsigned version){
a & id & name & salary;
}
public:
Employee(){}
Employee(int i, string n, float s):id(i),name(n),salary(s)
{}
};
int main()
{
const string filename = "emp.dat";
Employee e1(11,"Harry",4500.00f);
Employee e2(22,"Ravi",8800.00f);
Employee e3(33,"Tim",6800.00f);
Employee e4(44,"Rajiv",3400.00f);
// Serialize and persist the object
{
std::ofstream outfile(filename);
boost::archive::text_oarchive archive(outfile);
archive << e1 << e2 << e3 << e4;
}
// Deserialize and restore the object
Employee restored_e1;
Employee restored_e2;
Employee restored_e3;
Employee restored_e4;
{
std::ifstream infile(filename);
boost::archive::text_iarchive archive(infile);
archive >> restored_e1 >> restored_e2
>> restored_e3 >> restored_e4;
}
return 0;
}
【问题讨论】:
-
I guess that this protocol does not work for files,为什么你猜我们不能通过 TCP 发送文件?您没有从网站下载任何文本吗? -
@prehistoricpenguin 是的,它不适用于文件
标签: c++ serialization boost deserialization