将指针的向量存储在文件中并再次读取 [英] Storing vector of pointers in a file and reading them again

查看:139
本文介绍了将指针的向量存储在文件中并再次读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有以下代码:

// Base class
class Base {
public:
    Base(int val) : hi(val) {
    }
    virtual void PublicMethod() { /* Do something */}

private:
    int hi;
};

// Child class
class Child : public Base {
public:
    Child(int val) : Base(val) {
    }
    void PublicMethod() { /* Do something */}
};

// Vector of pointers to prevent slicing
std::vector<std::shared_ptr<Base>> list;

(...) // Fill list with mixed data of class Base and Child


$ b b

在列表填充了对象之后,我想将数据存储到文件中。为此,我尝试以下:

After the list is filled with objects, I want to store the data into a file. For this I tried the following:

std::ofstream os("data.txt", std::ios::out);

int size1 = list.size();
os.write((const char*)&size1, sizeof(int));
for (auto it = list.begin(); it < list.end(); ++it) {
    os.write((const char*)(*it), size1 * sizeof(Base));
}
os.close();

但我不知道这是否正确,并且从文件读取数据也不似乎工作正常。恐怕当我保存数据 sizeof(Base)也不适用于其子对象,可能不是相同的大小。

However I am not sure if this is correct, and reading the data from the file also doesn't seem to work properly. I am afraid that when I'm saving the data sizeof(Base) also doesn't work for its child objects which might no be of the same size.

即使这样工作正常,是否有更好的方式将实际数据存储到文件中,以及如何从文件中轻松读取数据并将它们存储在 shared_ptr< Base> 向量列表?

Even if this works correctly, are there better ways of storing the actual data into a file, and how can I easily read the data from the file and store them in a shared_ptr<Base> vector list?

任何例子都有很大的帮助。

Any examples would be of great help.

推荐答案

您需要为对象提供某种形式的序列化。这里有一个非常简单的例子(不包括错误检查,类型构造等)。

You need to provide some form of serialization for your objects. Here's a very trivial example (that leaves out error checking, type construction etc.)

这个例子展示了最原始的序列化类型,但它足以提供一个例子你需要做什么。

This example shows most primitive type of serialization, but it will suffice to provide an example of what you need to do.

当你开始处理派生类时,它变得更棘手,因为你需要一些工厂方法来正确创建类型,基于一些

When you start dealing with derived classes, it becomes more tricky, as you will need some factory method to properly create the types, based on some sentinel value that you serialize.

#include <string>
#include <iostream>
#include <sstream>
using namespace std;

class A
{
public:
    A()
        : a_(0)
    {
    }

    A(int a, const string& n)
        : a_(a), n_(n)
    {
    }

    // a function to write objects to a stream    
    friend ostream& operator<<(ostream& stream, const A& obj);

    // a function to read objects from a stream
    friend istream& operator>>(istream& stream, A& obj);

private:
    int a_;
    string n_;
};

ostream& operator<<(ostream& out, const A& obj)
{
    out << obj.a_ << ' ' << obj.n_;
    return out;
}

istream& operator>>(istream& in, A& obj)
{
    in >> obj.a_ >> obj.n_;
    return in;
}


int main()
{
    A one(1, "one");
    A also_one;

    string buffer;
    stringstream serializer;

    // write out your source object to a stream and "store it"
    // here we simply store it in a string    
    serializer << one;
    buffer = serializer.str();

    // using the "stored" value, read the stored values
    // into an (already constructed) object
    stringstream deserializer(buffer);
    serializer >> also_one;

    // verify the output is the same
    cout << one << " is the same as " << also_one << "\n";
}

这篇关于将指针的向量存储在文件中并再次读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆