从多个类中保存变量

Saving variables from multiple classes to file

本文关键字:保存 变量      更新时间:2023-10-16

对于我当前的项目,我希望最终能够将游戏状态保存到文件中。

我希望拥有一个非常简单的系统,其中我以ASCII格式存储所需的变量数据。
但是。我如何收集所有变量?

做i

  • 将Ofstream(文件流(对象传递到所有必需的类?
  • 通过一些getter方法获取变量?
  • 将它们全部存放在一个地方?
  • 其他?

当然,我还必须稍后从文件初始化var。

我似乎很难在这里做出决定。所以我谦虚地要求一些提示。

欢呼!

注意:我在年龄段还没有使用C ,因此语法/库函数的使用并不完全准确。希望它确实能实现这个想法。

为救援设计模式!将一些处理程序注册到Save类中,该类将为您保存每个变量。

首先,我们定义一个接口:

class ISerializable {
public:
    virtual std::vector<byte> serialize() { throw new NotImplementedException; }
}

接下来,我们编写Save类来保存每个处理程序:

class Save {
    std::map<std::string, ISerializable> handlers;
public:
    void save(string filename) {
        // Open file as writeable bytes
        std::ofstream outFile(filename, std::binary | std::trunc);
        // You may want to use an iterator here.
        // I forgot the exact syntax.
        // pair.Key is the name
        // pair.Value is the class you are saving
        foreach(pair in handlers) {
            // This is an example.
            // Your actual file format will be a bit more complicated than this.
            outFile << "Name: " << pair.Key
                << "Data: " << pair.Value.serialize();
        }
    }
    void attachHandler(std::string name, ISerializable handler) {
        handlers[name] = handler;
    }
}

然后,对于要保存的每个变量,为其类定义一个序列化函数:

class MyObject : public ISerializable {
public:
    std::vector<byte> serialize override {
        // return some list of bytes
    }
}

并将其处理程序附加到Save实例:

Save save; // Instantiate your saving object.
           // Consider making this static.
MyObject myObject;
save.attachHandler("myObject", myObject);

您可能需要将XML视为存储格式:如果不正确完成,存储原始字节可能很棘手。