當聲明與值參數的函數,如
void func(int i)
您聲明輸入。
#include <iostream>
void func(int i)
{
// the 'i' you see here is a local variable.
i = 10;
// we changed the local thing called 'i', when
// we exit in a moment that 'i' will go away.
}
int main()
{
int i = 1;
func(i);
// if we print 'i' here, it will be our version of i.
std::cout << "i = " << i << '\n';
return 0;
}
i
的參數func
是本地func
;這會讓新的C++程序員感到困惑,特別是在上面的場景中,它看起來像是將i
本身傳遞給func,而不是通過main :: i的值。當你進一步學習C/C++時,你會發現'參考'和'指針'類型,它們允許你實際地將變量轉發給函數而不是它們的值。
當你的函數實際上正在獲取一個用戶輸入值,然後將它傳遞給調用者或返回它。
int attempt()
{
std::cout << "Take a guess!\n";
int guess;
std::cin >> guess;
return guess;
}
我們告訴大家,「嘗試」不帶參數的編譯器和將回一個int值。然後在函數的最後,我們使用return
來做到這一點。
return
只能傳回一個值 - 稍後您將瞭解指針和引用,這將允許您返回大於單個值的內容。
要獲得這個價值,你的主:
int main() {
int answer = (rand() % 10) + 1;
srand(time(0));
std::cout << "I am thinking of a number between 1 and 10. Try to guess it in 3 attempts!";
std::cout << endl;
int guess = attempt();
std::cout << "You guessed: " << guess << '\n';
cin.get();
return 0;
}
或者把變量的聲明,並使用了兩行:
int guess;
...
guess = attempt;
一個重要的事情,從這個全部拿走的是,你可以在不同'範圍'中使用相同名稱的不同變量:
int i = 1; // global, visible to all functions in this compilation unit.
int main()
{
srand(time());
int i = 2;
if ((rand() % 4) == 0) // 1 in four chance
{
// this is essentially a new scope.
int i = 10;
}
// here, i = 2.
}
void foo()
{
// here, i = 1 - we see the global since we didn't declare our own.
}
void foo2(int i)
{
// here, i is whatever value we were called with.
if (i == 1)
{
int i = 99;
}
// we're back to the i we were called with.
}
一個非常基本的5yo類型問題:你得到什麼錯誤? – 2014-01-29 02:30:33
這與ELI5沒有任何關係,是嗎? – chris
'int attempt(int guess)'應該是'int attempt(int&guess)',而在main,'attempt();'應該傳遞'int&'。在編寫代碼之前學習C++的基礎知識會更好。 – Mine