C ++函数未声明?

时间:2016-10-07 03:08:40

标签: c++ function

我尝试制作命令行游戏并宣布这两个函数但是当我调用playerAttack();时,构建消息显示为error: playerAttack start was not declared in this scope我声明了函数playerAttack()和{在cpuAttack()函数之前{1}}如果有帮助的话。请提前帮助你。

int main() {...}

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";
    }
}

1 个答案:

答案 0 :(得分:1)

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

void cpuAttack();
void playerAttack();

// now define them ...

或者,你可以通过允许其他东西控制转向来消除相互依赖,从而不会在彼此之上堆叠调用(在某些情况下可能会导致堆栈溢出)。