繁体   English   中英

C++ 函数未声明?

[英]C++ Functions not declared?

我正在尝试制作一个命令行游戏,并声明了这两个函数,但是当我调用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 ...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM