未声明的c++函数

C++ Functions not declared?

本文关键字:函数 c++ 未声明      更新时间:2023-10-16

我试图做一个命令行游戏,我声明这两个函数,但当我调用playerAttack();构建消息说error: playerAttack start was not declared in this scope我在int main() {...}函数之前声明了playerAttack()cpuAttack(),如果这有帮助的话。请帮忙提前致谢。

void cpuAttack() {
    if (playerHealth > 0 && cpuHealth > 0) {
        cout << "Attack Direction (left, right, or center): ";
        cin >> attack;
        cout << name << " attacks from the " << attack << endl;
        srand(time(0));
        cpuBlock = attDir[rand() % 2];
        cout << "CPU-1 blocks the " << cpuBlock << endl;
        if (attack != cpuBlock) {
            cpuHealth - dmg;
        } else {cpuHealth = cpuHealth - (dmg + 20);}
        playerAttack();
    } else if (playerHealth > 0 && cpuHealth <= 0) {
        cout << "n" << name << " has won the game.n";
    } else if (playerHealth <= 0 && cpuHealth > 0) {
        cout << "nCPU-1 has won the game.n";
    }
}

void playerAttack() {
    if (playerHealth > 0 && cpuHealth > 0) {
        cout << "Attack Direction (left, right, or center): ";
        cin >> attack;
        cout << name << " attacks from the " << attack << endl;
        srand(time(0));
        cpuBlock = attDir[rand() % 2];
        cout << "CPU-1 blocks the " << cpuBlock << endl;
        if (attack != cpuBlock) {
            cpuHealth - dmg;
        } else {cpuHealth = cpuHealth - (dmg + 20);}
        cpuAttack();
    } else if (playerHealth > 0 && cpuHealth <= 0) {
        cout << "n" << name << " has won the game.n";
    } else if (playerHealth <= 0 && cpuHealth > 0) {
        cout << "nCPU-1 has won the game.n";
    }
}

因为这两个函数是相互依赖的,所以其中一个函数在定义之前必须已经知道另一个函数。解决方案是在定义之前声明它们:

void cpuAttack();
void playerAttack();
// now define them ...

或者,您可以通过允许其他东西控制轮询来摆脱相互依赖,从而不将调用堆叠在彼此的顶部(这可能在某些情况下导致堆栈溢出)。