2015-11-19 20 views
-16

嘿StackOverflow的社區,這個問題是關於C++編程,以及如何從內部在主叫發生同樣的程序調用一個函數。此外,我已經研究並查找了其他堆棧溢出問題和答案,我也在網上尋找答案,但他們沒有給我具體的答案,我正在尋找。無論如何,繼續這個問題......我正在尋找使用最佳實踐從C++程序中調用C++函數的正確/最有效的方法。我試圖做這樣的事情......如何調用C++函數的C++程序

//Even Odd Determiner VTew 
#include <iostream> 
#include <iomanip> 
using namespace std; 

int main(){ 
program(); 
} 

int program() 
{ 
unsigned int UserNum; 
bool Odd; 
bool True; 

system ("cls"); 

cout << "User, this program is an Even/Odd Determiner.\n"; 
cout << "Please input a number that you would like to\n"; 
cout << "be determined as either Even or Odd: "; 

cin >> UserNum; 

system ("pause"); 
system ("cls"); 

if (UserNum % 2 == 1) 
{ 
    cout << "Your number is odd!\n\n"; 
} 
if (UserNum % 2 == 0) 
{ 
    cout << "Your number is even!\n\n"; 
}else 
{ 
    cout << "Invalid Input"; 
    program(); 
} 



system ("pause"); 
return 0; 
} 

但這不能正常工作,沒有任何人知道如何做到這一點,其他網站/問題,回答它,那將是巨大的:)。 順便說一句我正在使用Visual Studio 2012 Premium。 -Garrett O'Canna(版本克斯圖C++程序員和視頻遊戲開發商) 更新:西蒙建議我說出具體的問題...系統尚未宣佈,編譯器,因爲我試圖調用一個函數弄糊塗了直到後來纔在程序中聲明)。

+0

你能澄清你所說的「這不能正常工作」是什麼意思?你是否打電話給「program()」?如果是這樣,那麼它產生的輸出與你預期它應該產生的輸出相比呢? – Simon

+2

沒有辦法,你不能找到谷歌這個問題的答案搜索... –

+0

@LukePark其實我敢打賭,它很難找到比你想象的。當你知道答案的時候很容易,因爲你知道要搜索什麼。對於新程序員來說,這種行爲是一個驚喜,他們不知道要搜索什麼。他說,他打量了一番 - 我相信他 – pm100

回答

4

的功能程序不知道的編譯器,因爲它是你的主要功能後,宣佈返回program()返回值。當你新的C/C您必須在這樣聲明

int program(); // Declares the function program 

int main() 
{ 
    program(); // function is declared, the compiler knows its return-type, name and parameters 
    return 0; 
} 

// Here is the function definition 
int program() 
{ 
    // .... 
} 

一個簡單的方法去思考++是編譯器的工作原理通過文件「自上而下」。這意味着你不能用一個變量/方法X已經聲明之前。

你必須做同樣的變量。一個簡單的例子

#include <iostream> 

// Declare an integer variable called b. The use of the word 
// extern means that the variable is just declared, not initialized 
extern int b; 

int main() 
{ 
    // This will compile, you have declared b above so the compiler "knows" about b 
    std::cout << "b = " << b << std::endl; 
    return 0; 
} 

int b = 7; // define b 
+0

很好回答!謝謝! –

+0

@VersionTew不客氣!歡迎來到論壇! – jensa

+0

不完全正確。 OP也可以聲明main之上的整個函數(或變量)。使用這個答案提出的前向聲明方法,現在有兩個變化,如果'程序'的簽名發生了變化,就必須做出兩個變更。忘記改變一個,你會有一個糟糕的一天。幸運的是,鏈接器應該捕獲錯誤並給你另一個有趣的錯誤信息來解碼。 – user4581301

3

所有你需要做的是使之main()之前出現要麼移動整個功能或把它在那裏,但通過main()前加入

int program(); 

main()前申報。您必須在main()之前聲明或定義該函數 - 兩種方法都可以讓您做你想做的事情。

您可能還需要從您的main()功能