如何在定义它的同一结构中使用变量?

How to use a variable in the same struct it's defined in?

我正在制作一个类似 rogue 的 ASCII 游戏,并制作了一个名为 "Armor" 的结构,我想在结构中使用名称变量来获取名称的路径。

struct Armor {
    bool equipped;
    std::string name;

    int getBuff(int buff) {
        std::fstream item;
        std::string line;
        std::string response;
        std::string value;

        item.open("../Data/Items/" + name + ".item", std::fstream::in);
        if (item.fail())
            errorQuit("ERROR: There was a problem loading armor type .ITEM file."); // Error and quit function

        while (!item.eof()) {
            getline(item, line);
            response = split(line, '=', 0); // Splits string
            if (response == "buff" + std::to_string(buff)) {
                value = split(line, '=', 1);
                break;
            }
        }

        item.close();
        return std::stoi(value);
    }

};

然后我这样称呼它:

Armor sword;
    sword.name = "Wooden Sword";
    int buff = sword.getBuff(1);

但这会引发未处理的异常错误。 我更改了它,以便 getBuff 接受 2 个参数,int buff 和 std::string itemName。并将路径中的名称替换为 itemName; 然后我试着这样称呼它:

Armor sword;
    sword.name = "Wooden Sword";
    int buff = sword.getBuff(1, sword.name);

但这会引发同样的错误。

我很困惑为什么我不能使用名称变量,因为它已经被定义了。有没有其他方法可以像那样使用名称变量?

您的 getBuf() 函数在某些 io 操作上失败并抛出 exception.You 不处理异常,因此应用程序退出并显示适当的消息。尝试用 try/catch 包围对 getBuf 的调用(将包含添加到 iostream 和 stdexcept)

try {
  int buff = sword.getBuff(1);
}
catch (const std::exception &e) {
  std::cout << e.what() << std::endl;
}

感谢您的帮助,但我自己弄明白了。

我刚刚犯了一个愚蠢的错误,我像个白痴一样忽视了。

它正在文件中搜索 buff + int (e.x.buff1),但有多行包含该词,所以我猜它搞砸了。我刚刚对 if 语句进行了调整,它按预期工作。

抱歉打扰了!

我看到你刚刚编辑了你的评论,说你已经解决了你的问题,但我只想添加一些可能有用的东西:

没有看到 errorQuit() 是如何定义的,您的 getBuff() 函数中可能存在问题。如果表达式 if (item.fail()) 的计算结果为真,该函数可能会继续尝试处理数据(除非 errorQuit() 以某种方式中断了程序或其他事情,这可能不是最好的方法)。

基本上,fail() 的测试可能会或可能不会提供您在所有情况下所需的行为,具体取决于流状态中设置的位。实现方式各不相同,但是...如果文件无法打开,将设置 failbit and/or badbit,而不是 eofbitgetline() 将看到错误状态,因此当您调用它时它不会尝试从流中读取。但这也意味着 eofbit 永远不会被设置!

文件阅读有很多不同的"techniques"。有些人更喜欢 RAII 方法。其他人喜欢在 getline() 上循环播放。或者,如果您不关心发生了什么,只是想知道是否一切正常,您甚至可以使用 good() 来检查错误状态。

无论如何,您可能对此页面上的信息感兴趣:std::ios_base::iostate