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

时间:2018-05-13 01:28:39

标签: 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:
        {
            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;
        }
    }
}

我想不出任何其他方法可以解决这个问题,但事实证明,它根本不起作用。

我得到的唯一错误是稍后当我想访问我假设这段代码正确加载的数据时的运行时访问冲突。

Line和Circle来自父对象Shape。

异构集合的保存功能:

void HeterogeneousCollection::save(std::ostream& os) const {
    os << size << std::endl;
    for (size_t i = 0; i < size; i++) {
        os << (*this)[i].getId() << std::endl;
        (*this)[i].save(os);
    }
}

Shape的保存和加载功能:

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);
}

Line的保存和加载功能:

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);
}

我正在尝试读取的文件,由之前调用的HeteroStore的save()生成:

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

1 个答案:

答案 0 :(得分:0)

我想通了,每次将指针添加到异构集合时,add()函数都会递增大小,因此size(在load函数开头初始化为非零)将不能正确表示存储的大小并且依赖它的商店的每个功能都将被打破。 例如,在save()函数中,for循环将运行得太多,并且需要访问非现有指针,因为错误显示正确。

解决方案:

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

    is >> sizeofotherstore;

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