You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++类方法读取文件赋值私有成员:英雄存档加载问题

核心问题与解决方案

1. 参数传递错误,原对象未被修改

loadgame函数中的hero newhero是值传递,你修改的只是传入对象的临时副本,原herosave对象根本不会发生变化。必须改成引用传递:

void loadgame(int save, hero &newhero){ // 加&改为引用
    // ... 原有代码
}

2. 文件名拼写错误

当save == 3时,你打开的是hero2.txt,应该改为hero3.txt,否则会读错存档文件。

3. 带空格的字符串读取不完整

你的存档中姓名是Bilbo Baggins,用file >> name只能读取到第一个空格前的Bilbo,必须用getline读取整行内容:

getline(file, name); // 读取包含空格的完整姓名

4. loadStats仅读取了name,未处理其他成员

需要按照存档文件的顺序,完整读取所有私有成员:

void hero::loadStats(ifstream &file){
    // 读取字符串类型成员,每行一个
    getline(file, name);
    getline(file, race);
    getline(file, heroclass);
    // 读取整数类型成员,>>会自动跳过换行/空格
    file >> strength;
    file >> wisdom;
    file >> charisma;
    file >> dexterity;
    file >> intelligence;
    file >> constitution;
    // 注意:存档文件最后一行的16对应哪个成员?根据你的类定义,还有hitpoints和AC未读取,需要对应存档时的输出顺序调整
}

可选优化:增加文件打开校验

避免因文件不存在/权限问题导致的读取失败,建议在打开文件后增加校验:

ifstream file1("hero1.txt");
if (!file1.is_open()) {
    // 这里可以加错误提示,比如cout << "存档文件1打开失败" << endl;
    return;
}
newhero.loadStats(file1);
file1.close();

内容的提问来源于stack exchange,提问作者Jonathan Tyler Ecton-Rodriguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:03:23