Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;如何从文件加载异构集合_C++_Serialization - Fatal编程技术网

C++ c++;如何从文件加载异构集合

C++ c++;如何从文件加载异构集合,c++,serialization,C++,Serialization,我想创建一个异构集合,它能够从文件中加载自己 我有以下代码: void HeterogeneousCollection::load(std::istream& is) { is >> size; for (size_t i = 0; i<size; ++i) { int id; is >> id; switch (id) { case 0: {

我想创建一个异构集合,它能够从文件中加载自己

我有以下代码:

void HeterogeneousCollection::load(std::istream& is) {

    is >> size;

    for (size_t i = 0; i<size; ++i)
    {
        int id;
        is >> id;
        switch (id) {
        case 0:
        {
            Line* line = new Line;
            line->load(is);
            this->add(line);
        }
        case 1:
        {
            Circle* circle = new Circle;
            circle->load(is);
            this->add(circle);
            break;
        }
        default:
            break;
        }
    }
}
我试图读取的文件,由先前调用heforStore的save()生成:

我发现,add()函数在每次向异构集合添加指针时都会增加大小,因此大小(在加载函数开始时初始化为非零)将不能正确表示存储的大小,并且依赖它的存储的每个函数都将彻底崩溃。 例如,在save()函数中,For循环将运行过多,并且需要访问不存在的指针,正如错误正确显示的那样

解决方案:

void HeterogeneousCollection::load(std::istream& is) {

    is >> sizeofotherstore;

    for (size_t i = 0; i<sizeofotherstore; ++i)
void HeterogeneousCollection::load(std::istream&is){
is>>sizeofotherstore;
对于(尺寸i=0;i
void Shape::save(std::ostream& os) const
{
    os << id << std::endl;
    color.save(os);
    pos.save(os);
}

void Shape::load(std::istream& is)
{
    is >> id;
    color.load(is);
    pos.load(is);
}
void Line::save(std::ostream& os) const 
{
    Shape::save(os);
    P1.save(os);
    P2.save(os);
}

void Line::load(std::istream& is) 
{
    Shape::load(is);
    P1.load(is);
    P2.load(is);
}
2 //size of store
0 //id of a Line
0 //R of color of a Line
0 //G of color of a Line
0 //B of color of a Line
23 //X of position of a Line
12 //Y of position of a Line
23 //X of a point of a Line
12 //Y of a point of a Line
49 //X of another point of a Line
6  //Y of another point of a Line
1  //id of a Circle
0 //R of color of a Circle
0 //G of color of a Circle
0 //B of color of a Circle
10 //X of position of a Circle
10 //Y of position of a Circle
10 //radius of a Circle
void HeterogeneousCollection::load(std::istream& is) {

    is >> sizeofotherstore;

    for (size_t i = 0; i<sizeofotherstore; ++i)