我不知道如何实现类A
, C
or D
,但这是第一个问题:如何序列化该类的对象。为了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()
and read()
该类的函数。
好吧,如果你想序列化一个vector<shared_ptr<C>>
看起来很明显你不想序列化指针,而是序列化内容。因此,您需要取消引用每个指针并进行序列化。如果在加载之前未知向量的大小(即并不总是相同),则您需要存储该信息。然后,您可以创建一对函数来序列化完整的向量:
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;
};
我知道你还有很多事情需要解决。我建议您进行调查以解决这些问题,以便您充分了解如何解决您的问题。