gpt4 book ai didi

c++ - 使用序列化 C++ 保存游戏状态

转载 作者:行者123 更新时间:2023-11-30 02:46:43 63 4
gpt4 key购买 nike

我有一个名为 Game 的类,其中包含以下内容:

vector<shared_ptr<A>> attr; // attributes
D diff; // differences
vector<shared_ptr<C>> change; // change

我的问题是,如何将这些(保存)写入文件并稍后读取/加载?我考虑过在其中使用 struct 并简单地保存 struct 但我不知道从哪里开始。

到目前为止,这是我的尝试,只是试图保存更改。我已经阅读了很多关于这个问题和我的问题(无论如何,其中一个)似乎是我正在存储指针,这些指针在关闭程序后将无效(由于我在退出之前也释放了它们而变得更加复杂).

/* Saves state to file */
void Game::saveGame(string toFile) {
ofstream ofs(toFile, ios::binary);
ofs.write((char *)&this->change, sizeof(C));

/* Free memory code here */
....

exit(0);
};

/* Loads game state from file */
void Game::loadGame(string fromFile) {
ifstream ifs(fromFile, ios::binary);
ifs.read((char *)&this->change, sizeof(C));

this->change.toString(); // display load results
};

任何人都可以指导我在正确的方向上序列化这些数据吗?我只想使用标准包,所以没有 boost

谢谢。

最佳答案

我不知道类是如何实现的A , CD ,但这是第一个问题:如何序列化该类的对象。对于 C在这种情况下,您需要执行如下操作:

std::ostream& operator <<(std::ostream& os, const C& c) {
// ... code to serialize c to an output stream
return os;
}
std::istream& operator >>(std::istream& is, C& c) {
// ... code to populate c contents from the input stream
return is;
}

或者,如果您愿意,可以创建一个 write()read()该类的函数。

好吧,如果你想序列化一个vector<shared_ptr<C>>看起来很明显你不想序列化指针,而是序列化内容。所以你需要取消引用每个指针并序列化。如果在加载之前不知道 vector 的大小(即,并不总是相同的),则需要存储该信息。然后,您可以创建一对函数来序列化完整的 vector :

std::ostream& operator <<(std::ostream& os, const std::vector<std::shared_ptr<C>>& vc) {
// serialize the size of the vector using << operator
// for each element of the vector, let it be called 'pc'
os << *pc << std::endl; // store the element pointed by the pointer, not the pointer.
return os;
}
std::istream& operator >>(std::istream& is, std::vector<std::shared_ptr<C>>& c) {
// read the size of the vector using >> operator
// set the size of the vector
// for each i < sizeo of the vector, let 'auto &pc = vc[i]' be a reference to the i-th element of the vector
C c; // temporary object
is >> c; // read the object stored in the stream
pc = std::make_shared<C>(c); // construct the shared pointer, assuming the class C has copy constructor

return is;
}

然后,

/* Saves state to file */
void Game::saveGame(string toFile) {
ofstream ofs(toFile);
ofs << change;
....
};

/* Loads game state from file */
void Game::loadGame(string fromFile) {
ifstream ifs(fromFile);
ifs >> change;
};

我知道你还有很多事情需要解决。我建议您进行调查以解决这些问题,以便您了解如何解决您的问题。

关于c++ - 使用序列化 C++ 保存游戏状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23357553/

63 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com