面试题整理-C++ 序列化对象
来源:互联网 发布:美国囧哥百货 淘宝 编辑:程序博客网 时间:2024/05/21 06:55
题目:在C++里面,两台机器之间的函数相互调用,需要传递对象。采用什么样的方法可以把C++对象序列化之后,在两台机器之间,像字符串一样传输。解法:想到boost库中是有一个序列化类的。在这里,我们直接利用这个类来进行处理。
#include <fstream>#include <sstream>#include <iostream>#include <boost/archive/text_oarchive.hpp>#include <boost/archive/text_iarchive.hpp>using namespace std;class gps_position{private: friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & degrees; ar & minutes; ar & seconds; } int degrees; int minutes; float seconds;public: gps_position() { degrees = 0; minutes = 0; seconds = 0.0; }; gps_position(int d, int m, float s) : degrees(d), minutes(m), seconds(s) {}};class bus_stop{ friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & latitude; ar & longitude; } gps_position latitude; gps_position longitude;public: bus_stop(){ } bus_stop(const gps_position & lat_, const gps_position & long_) : latitude(lat_), longitude(long_){ } virtual ~bus_stop(){ }}; class bus_stop_corner : public bus_stop{ friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & boost::serialization::base_object<bus_stop>(*this); ar & street1; ar & street2; } std::string street1; std::string street2;public: bus_stop_corner(){} bus_stop_corner(const gps_position & lat_, const gps_position & long_, const std::string & s1_, const std::string & s2_ ) : bus_stop(lat_, long_), street1(s1_), street2(s2_) {} virtual std::string description() const { return street1 + " and " + street2; }};int main() { const gps_position latitude(1, 2, 3.3f); const gps_position longitude(4, 5, 6.6f); bus_stop_corner stop_corner(latitude, longitude, "corn1", "corn2"); ostringstream ostr; { boost::archive::text_oarchive oa(ostr); oa << stop_corner; } string comment = ostr.str(); cout << comment << endl; istringstream iis(comment); bus_stop_corner new_stop_corner; { istringstream istr; boost::archive::text_iarchive ia(iis); ia >> new_stop_corner; } return 0;}
这里使用的是boost的序列化操作。
首先安装boost库。
apt-get install libboost1.48-all-dev
编译
g++ test.cpp -o test -lboost_serialization
- 面试题整理-C++ 序列化对象
- 【C#】面试题整理
- 【C#】面试题整理
- C面试题整理
- 面试题--对象序列持久化
- 面试题--对象序列持久化
- Java面试题【对象序列化】
- 【Killua笔试面试题整理】二进制序列
- C++面向对象面试题知识点整理
- C/C++面试题(整理)
- 整理的C、C++面试题
- 《C语言深度解剖》面试题整理
- 《C语言深度剖析》面试题整理
- C/C++常见面试题整理
- 面试题整理6 栈的压入、弹出序列
- 面试题:Java中对象序列化接口(Serializable)的意义
- 面试题:Java中对象序列化接口(Serializable)的意义
- 《高质量程序设计指南:C++/C语言》面试题整理
- HDU 1421 差的平方和最小
- unix时间值转指定格式的时间串
- Android下Xml解析技术(四)、pull生成Xml文件
- 利用OSGi开发WEB应用
- 一个查看Http数据工具
- 面试题整理-C++ 序列化对象
- mysql build and setup on linux
- zip4j -- Java处理zip压缩文件的完整解决方案
- bat win7 检测程序是否已管理员身份运行
- javascript var
- JavaScript中的Timer是怎么工作的
- 图文介绍Android环境搭建详细步骤
- 从远程服务器下载文件到本地服务器
- PHP程序编写规则