2016-10-07 135 views
-1

我想做一個命令行遊戲,我聲明瞭這兩個函數,但是當我呼叫playerAttack();構建消息說error: playerAttack start was not declared in this scope我宣佈功能playerAttack()cpuAttack()int main() {...}功能之前,如果有幫助。請提前幫助謝謝你。未聲明C++函數?

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

你在'main'之前聲明'playerAttack',你說,但是你在'cpuAttack'之前聲明瞭嗎? – immibis

+0

@immibis當我在'cpuAttack'之前聲明它時我得到'錯誤:cpuAttack未在此範圍內聲明。 –

回答

1

由於兩個函數是互相依賴於彼此,它們中的一個必須已經知道其他定義了一個前。解決的辦法是事先宣佈他們的定義:

void cpuAttack(); 
void playerAttack(); 

// now define them ... 

或者,你可以擺脫相互依存的,允許別的東西,以控制接通回吐,因而不能堆放在彼此的頂部電話(其可能會在某些情況下導致堆棧溢出)。