1

序列化有很多答案。

对于 C++ 中的序列化/重构,这是我的代码:

#include <string>
#include "Student.h"
#include <iostream>
#include <fstream>
#include <ostream>
#include <sstream>
#include <boost\archive\xml_oarchive.hpp>
#include <boost\archive\xml_iarchive.hpp>
#include <boost\archive\binary_oarchive.hpp>
#include <boost\archive\binary_iarchive.hpp>

using namespace std;


void serialization();
void reconstruction();
int main()
{
    serialization();
    reconstruction();
    getchar();
    return 0;
}

void serialization(){
    int id = 100;
    string name = "Mike";
    Student student(id ,name);
    string filename("student.xml");
    std::ofstream ostreamXml(filename.c_str());
    boost::archive::xml_oarchive oabin(ostreamXml);
    oabin<<BOOST_SERIALIZATION_NVP(student);
    ostreamXml.close();
}

void reconstruction(){
    std::ifstream inputStream("student.xml");
    boost::archive::xml_iarchive iArchive(inputStream);
    Student student2(2,"dfds");
    iArchive>> BOOST_SERIALIZATION_NVP(student2);
    inputStream.close();
    cout<<student2.takeExam(2,3);
}

在这种情况下,我可以重建对象,因为我知道序列化对象的类型,即“学生”。但是如果我不知道要反序列化的对象的类型怎么办?

谢谢!

4

0 回答 0