2016-09-30 1825 views
-1

爲什麼我從編譯器中獲得this error關於不帶0參數的函數?是因爲我在被調用之後聲明函數?C++函數不接受0參數

// HelloWorld.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include <iostream> 


using namespace std; 

int main() 
{ 
    cout << "Hello World!\n"; 
    cout << "Game over!\n"; 
    swap(); 
    system("pause"); 
    return 0; 
} 

int swap() 
{ 
    int on = 1; 
    int off = 0; 
    int temp = on; 
    on = off; 
    off = temp; 
    return 0; 
} 

enter image description here

+2

您需要在使用它之前聲明的一切。 –

+4

避免'使用namespace std'並定義一個具有相同名稱的函數...... – Jarod42

+5

這是因爲你被代碼中'using namespace std;'行燒燬了。猜猜編譯器從哪裏獲得'swap'? – PaulMcKenzie

回答

4

是因爲我聲明函數已經調用後?

是的。

當編譯器看到swap()的調用時,它還不知道你的功能。在這種情況下,您通常會遇到「調用未聲明的函數」的錯誤,如果不是(它帶有兩個參數),那麼您已通過using namespace std指令將其拉入名稱空間。

爲了固定:移動的swap上述定義main(作爲一個函數定義總是還函數聲明)或離開它在那裏一個把一個專用聲明

int swap(); 

以上main 。正如你所看到的,我也擺脫了using namespace std;,因爲它可能會對你造成更大的傷害,而不是最好的,而是用std::明確地加上所有標準庫類型和函數的前綴。但這不是強制性的,也不是當前問題的根本原因。

1

嘗試在主要上面定義的函數或只是宣佈在main.It的頂部現在要求從.net庫交換