1. 程式人生 > >序列化自定義類

序列化自定義類

#include <fstream>

#include<boost/archive/text_oarchive.hpp>

#include <boost/archive/text_iarchive.hpp>

#include <iostream>

#include <Eigen/Dense>

using namespace std;

using namespace Eigen;

 

class Point2D;

class Rect2D;

class Circle2D;

class Arc2D;

class Line2D;

class Angle2D;

 

class Point2D{

private:

    friend class boost::serialization::access;

        template<class Archive>

        void serialize(Archive & ar,const unsigned int version)

        {

            ar & m_x;

            ar & m_y;

        }

    double m_x;

    double m_y;

public:

    Point2D(double x,double y):m_x(x),m_y(y){}

    Point2D(){}

    ~Point2D(){}

    double x()const{return this->m_x;}

    double y()const{return this->m_y;}

    Vector2d toVector()const{return Vector2d(m_x,m_y);}

    Point2D operator +(Point2D point){return Point2D(point.x()+m_x,point.y()+m_y);}

    Point2D operator -(Point2D point){return Point2D(point.x()-m_x,point.y()-m_y);}

    Point2D operator *(double value){return Point2D(m_x*value,m_y*value);}

    

};

class Line2D{

private:

    friend class boost::serialization::access;

    template<class Archive>

    void serialize(Archive & ar,const unsigned int version)

    {

        ar & start_point;

        ar & end_point;

    }

    Point2D start_point;

    Point2D end_point;

    Vector2d direction;

    

public:

    Line2D(Point2D A,Point2D B):start_point(A),end_point(B){}

    Line2D(){}

    ~Line2D(){}

    Point2D get_start(){return this->start_point;}

    Point2D get_end(){return this->end_point;}

    //double length(){return }

    

};

 

class Rect2D{

private:

    double m_length;

    double m_width;

    Point2D m_center;//=Point2D(0,0);

    Vector2d direction;

public:

    Rect2D(double length,double width,Point2D center,Vector2d direction):m_length(length),m_width(width),m_center(center){}

    

    Rect2D(){}

    ~Rect2D(){}

    double width(){return this->m_width;}

    double length(){return this->m_length;}

    

};

 

 

int main()

{

    Point2D start=Point2D(2,5);

    Point2D end=Point2D(6,8);

    Line2D line=Line2D(start,end);

    std::ofstream ofs("filename.txt");

    boost::archive::text_oarchive oa(ofs);

    oa<<line;

    ofs.close();

    cout<<"serialization finished..."<<endl;

    //Vector2d vec;

    

    Line2D line_out;

    std::ifstream ifs("filename.txt",std::ios::binary);

    boost::archive::text_iarchive ia(ifs);

    ia>>line_out;

    cout<<line_out.get_start().x()<<line_out.get_start().y()<<line_out.get_end().x()<<line_out.get_end().y()<<endl;

    return 0;

}