【发布时间】:2021-12-03 22:14:35
【问题描述】:
我创建一个 D&D 引擎只是为了练习我的 C++ 技能并学习一些更深入的主题。目前,我正在构建一个系统来保存和加载角色。我有一个 Stats 类,它包含一个角色的所有统计信息,还有一个角色类,目前只有一个名称和一个 stats* 到该角色的 stats 对象。
到目前为止,我已经能够使用 boost 文本存档成功保存数据,现在切换到 boost 二进制存档。保存数据时它似乎可以工作,但是当我尝试加载数据时出现此错误:
“异常未处理 - VileEngine.exe Microsoft C++ 异常中 [内存地址] 处的未处理异常:内存位置 [不同内存地址] 处的 boost::archive::archive_exception”
我可以多次跳过这个错误,但是当程序运行和加载时,加载的字符的数据已经偏离了,所以我知道它必须是我保存它的方式,或者更有可能在我正在加载它的方式。我已经尝试通读 boost 文档,但找不到修复它的方法。我也尝试搜索其他帖子但找不到答案,或者我只是不明白答案。非常感谢任何帮助。
相关代码贴在下面。如果需要,我可以发布所有代码,但对于所有课程来说都相当多。
在 Character.hpp 中
private:
friend class boost::serialization::access; //allows serialization saving
//creates the template class used by boost to serialize the classes data
//serialize is call whenever this class is attempting to be saved
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar << name;
ar << *charStats;
ar << inventory;
}
/*********************************
* Data Members
***********************************/
std::string name;
Stats* charStats;
std::vector<std::string> inventory;
public:
Character();
void loadCharacter(std::string &charName); //saves all character details
void saveCharacter(); //loads all character details
在 Character.cpp 中
/*********************************************
Functions to save and load character details
**********************************************/
void Character::saveCharacter() {
//save all details of character to charactername.dat file
//create filename of format "CharacterName.dat"
std::string fileName = name + ".dat";
std::ofstream saveFile(fileName);
//create serialized archive and save this characters data
boost::archive::binary_oarchive outputArchive(saveFile);
outputArchive << this;
saveFile.close();
}
void Character::loadCharacter(std::string &charName) {
//load details of .dat file into character using the characters name
std::string fileName = charName + ".dat";
std::ifstream loadFile(fileName);
boost::archive::binary_iarchive inputArchive(loadFile);
inputArchive >> name;
Stats* temp = new Stats;
inputArchive >> temp;
charStats = temp;
inputArchive >> inventory;
loadFile.close();
}
在 Stats.hpp 中
private:
friend class boost::serialization::access; //allows serialization saving
//creates the template class used by boost to serialize the classes data
//serialize is call whenever this class is attempting to be saved
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & skillSet;
ar & subSkillMap;
ar & level;
ar & proficiencyBonus;
}
【问题讨论】:
标签: c++ serialization boost binary deserialization