0

我对 c++ 相当陌生。作为一个项目,我正在重写我用 python 编写的一个小游戏(我从来没有让它正常工作)。在编译期间,我收到此错误:错误:'operator-=' 不匹配</p>

我知道这个运算符存在于 c++ 中,那么为什么会出现这个错误?

代码:

void rpg() {
    cout << "This mode is not yet complete. It only contains a dungeon so far. I'm still working on the rest!";
    dgn();
}
void dgn() {
    int whp = 100;
    int mahp = 100;
    int hhp = 100;
    string m;
    int mhp;
    cout << "There are three passages. Do you take the first one, the second one, or the third one? (Give your answer in numbers)";
    int psg;
    cin >> psg;
    switch (psg) {
    case 1:
        m = "Troll";
        mhp = 80;
        break;
    case 2:
        m = "Goblin";
        mhp = 35;
        break;
    case 3:
        m = "Dragon";
        mhp = 120;
    }
    cout << "A ";
    cout << m;
    cout << " appears!";
    dgnrd(m, mhp, whp, mahp, hhp);
}

void dgnrd(string m, string mhp, int whp, int mahp, int hhp) {
    bool alive = true;
    while (alive) {
        string wa;
        string ma;
        string ha;
        cout << "What does Warrior do? ";
        cin >> wa;
        cout << "What does Mage do? ";
        cin >> ma;
        cout << "What does Healer do? ";
        cin >> ha;
        if (wa == "flameslash") {
            cout << "Warrior used Flame Slash!";
            mhp -= 20;
        }
        else if (wa == "dragonslash" && m == "Dragon") {
            cout << "Warrior used Dragon Slash!";
            mhp -= 80;
        }
        else if (wa == "dragonslash" && (m == "Troll" || m == "Goblin")) {
            cout << "Warrior's attack did no damage!";
        }
        if (ma == "icicledrop") {
            cout << "Mage used Icicle Drop!";
            mhp -= 30;
            mahp -= 10;
            whp -= 10;
            hhp -= 10;
        }
        else if (ma == "flamesofhell") {
            cout << "Mage used Flames of Hell!";
            mhp -= 75;
            mahp -= 50;
            whp -= 50;
            hhp -= 50;
        }
        else if (ma == "punch") {
            cout << "Mage used Punch!";
            mhp -= 5;
        }
    }
}
4

3 回答 3

2

dgn()中,你有

int mhp;

这是明智的,因为它是一个数字量。

但是随后您的辅助函数声明

string mhp

在参数列表中,这应该导致函数调用中的实际参数和形式参数之间的类型不匹配错误

dgnrd(m, mhp, whp, mahp, hhp);

修复它int& mhp,几个问题将立即消失。

请注意,&它创建了一个引用。这使得函数与其调用者共享变量,以便对调用者的副本进行更改。否则(按值传递)函数内部的所有更改都会在函数返回时消失。

于 2013-07-30T18:36:17.433 回答
1

原因是std::string没有运营商-=。有+=, 它附加到现有字符串,但运算符的语义-=不清楚。

除了那个明显的问题之外,dgnrd函数的参数类型与您传递给它的参数的类型不匹配。

于 2013-07-30T18:33:06.693 回答
0

您似乎在字符串而不是 int 上运行 -= 运算符。mhp是 a string,因此以下语句导致编译错误:

mhp -= 
于 2013-07-30T18:34:57.433 回答