基类指针的vector怎么存储派生类

本文展示了一个使用C++和Boost库进行对象序列化的示例。通过定义几个类层次结构并实现序列化功能,演示了如何将对象状态保存到文件中。主要关注点在于序列化过程及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// SaveData.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>

#include <string>
#include <vector>
#include <iostream>
#include <sstream>  
#include <fstream>

class BaseOperator;

class findLineOperator;

BOOST_CLASS_EXPORT(BaseOperator)

BOOST_CLASS_EXPORT(findLineOperator)

using namespace std;

class BaseNode
{
public:
    virtual void print();
    std::string a="this is BaseNode a";
    std::string b="this is BaseNode b";
    //为使当前的结构能支持序列化,得加入下面的代码段
private:
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & a;
        ar & b;
    }
};

class BaseOperator :public BaseNode
{
public:
    std::string c = "this is BaseOperator c";
    std::string d = "this is BaseOperator d";
    virtual void print();
    //为使当前的结构能支持序列化,得加入下面的代码段
private:
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & boost::serialization::base_object<BaseNode>(*this);
        ar & c;
        ar & d;
    }
};
class findLineOperator :public BaseOperator {

public:
    int id=4;
    std::string strName="me";
    std::string strValue="you";

    virtual void print();
    findLineOperator() {}
    findLineOperator(int id, std::string strName, std::string strValue)
    {
        this->id = id;
        this->strName = strName;
        this->strValue = strValue;
    } 
};
void BaseNode::print()
{
    
}
void BaseOperator::print()
{

}
void findLineOperator::print()
{

}


class ToolBlock
{
public:
    std::vector<BaseNode*> listMR;
    
};


int main(int argc, _TCHAR* argv[])
{
    std::stringstream ss;

    //序列化
    //findLineOperator p1(11, "anderson", "neo");      //被序列化的对象
    ToolBlock *tool = new ToolBlock();

    BaseOperator *mr = new findLineOperator(99,"eric","lili");
    BaseOperator *mr2=new findLineOperator;

    std::vector<void*> listMR;

    //压入对象
    tool->listMR.push_back(mr);
    tool->listMR.push_back(mr2);

 

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

究极调参工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值