請看下面的代碼片段 - 我已經聲明瞭3個函數(即1傳遞一個int,其他傳遞一個int的引用)。執行程序後,我發現在調用函數(tripleByReference)之後,「count」變量的值沒有被改變以反映它的三元組(count仍然等於5)。然而調用函數(tripleByReferenceVoid)會修改變量,但這是由於直接對變量(count)發生更改的事實。C++參考和參考參數
我明白,通過引用傳遞,調用者給予被調用函數直接訪問調用者的數據並修改它的能力,但不能通過將該變量傳遞給函數來實現(tripleByReference) - 請幫助我理解這個。
#include <iostream>
using namespace std;
/* function Prototypes */
int tripleByValue(int);
int tripleByReference(int &);
void tripleByReferenceVoid(int &);
int main(void)
{
int count = 5;
//call by value
cout << "Value of count before passing by value is: " << count << endl;
cout << "Passing " << count << " by value, output is: "
<< tripleByValue(count) << endl;
cout << "Value of count after passing by value is: " << count << endl;
//call by reference - using int tripleByReference
cout << "\n\nValue of count before passing by reference is: " << count << endl;
cout << "Passing " << count << " by reference, output is: "
<< tripleByReference(count) << endl;
cout << "Value of count after passing by reference is: " << count << endl;
//call by reference - using void tripleByReference
tripleByReferenceVoid(count);
cout << "\n\nValue of count after passing by reference is: " << count << endl;
cout << endl;
system("PAUSE");
return 0;
}//end main
int tripleByValue (int count) {
int result = count * count * count;
return result;
}//end tirpleByValue function
int tripleByReference(int &count) {
int result = count * count * count;
return result; //perform calcs
}//end tripleByReference function
void tripleByReferenceVoid(int &count) {
count *= count * count;
}//end tripleByReference function
謝謝。
爲什麼'x * x'根本改變'x'? – chris 2012-07-05 19:08:24