-3
void func(int x) {
x = 2;
}
int main()
{
int x = 3;
func(x);
cout << "x = " << x << endl;
return 0;
}
我期望輸出爲2.爲什麼不會發生這種情況?一個簡單的解釋,因爲我只是剛開始學習C++請。你能不能再解釋一下爲什麼以下收益率5:爲什麼輸出不考慮函數?
void func(int x)
{
x = 2;
}
void function(int *x)
{
*x = 5;
}
int main()
{
int x = 3;
func(x);
function(&x);
cout << "x = "<< x << endl;
return 0;
}
可能重複的[當我更改函數中的參數,它是否更改爲調用者嗎?](http://stackoverflow.com/questions/1698660/when-i-change-a-parameter-inside - 一個功能,它也改變爲來電者)也 –
另請參見http://stackoverflow.com/questions/11736306/when-pass-a-variable-to-a-function-why-函數只得到一個重複的th,http://stackoverflow.com/questions/21215409/does-c-pass-objects-by-value-or-reference,以及一個關於C++的基本教程函數:http://www.cplusplus.com/doc/tutorial/functions/,以及您的指針示例:http://cslibrary.stanford.edu/104/(C++版本)。 –