c ++使用结构中的指针保存和加载游戏

The*_*des 5 c++ struct pointers file save

我知道我可以用:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
Run Code Online (Sandbox Code Playgroud)

保存并加载游戏,但如果我在MyGame结构中有指针怎么办?指针只会被保存但不会指向它指向的数据吗?

并且:如何解决这个问题?

Moo*_*ice 5

你不能只是编写一个指向流的指针,并希望它能够神奇地完成.您需要在对象中实现保存/加载方法.例如:

class Serializable
{
    virtual void save(std::ofstream& _out) const = 0;
    virtual void load(std::ifstream& _in) = 0;
}; // eo class Serializable


// some game object
class MyObject : public Serializable
{
    int myInt;
    std::string myString;

    virtual void save(std::ofstream& _out) const
    {
        _out << myInt << myString;
    }; // eo save

    virtual void load(std::ifstream& _in)
    {
        _in >> myInt >> myString;
    }; // eo load
}; // eo class SomeObject

class MyGame : public Serializable
{
    MyObject a;
    MyObject b;

    virtual void save(std::ofstream& _out) const
    {
        a.save(_out);
        b.save(_out);
    };  // eo save

    virtual void load(std::ifstream& _in)
    {
        a.load(_in);
        b.load(_in);
    };  // eo load
}; // eo class MyGame
Run Code Online (Sandbox Code Playgroud)