面试题整理-C++ 序列化对象

题目:在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++,String,serialization,Class,Access,archive)