从多个类中保存变量
Saving variables from multiple classes to file
对于我当前的项目,我希望最终能够将游戏状态保存到文件中。
我希望拥有一个非常简单的系统,其中我以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视为存储格式:如果不正确完成,存储原始字节可能很棘手。
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 无法通过头文件保存变量的值
- 一个变量的输入值也会保存到另一个变量中
- 是否可以在C++变量中保存多种类型的枚举?
- 如何在 c++ 中创建一个可以将自身保存为变量的类?
- 可视化C++从文件中保存/读取多个变量
- 将数据从 SQLite 数据库保存到变量中
- C++我应该用什么来保存格式化为字符串变量(如sprintf())的文件
- 指向结构变量的指针未保存到eeprom
- (C++)for循环中的空初始语句是否保存所有编译器中变量的上一次初始化
- 让类方法为每个实例保存不同的静态变量
- 在没有外部文件的情况下在应用会话之间保存变量
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 从多个类中保存变量
- 从保存变量数据类型的数据结构中检索值,而不指定返回类型
- 在程序关闭后,是否可以在内部保存变量并读/写入
- 为什么不保存变量中的更改
- 如何使用Q设置保存变量
- 如何在RAM中安全地保存c++变量
- 需要帮助关于通过fstream保存变量,我需要使用向量