请看下面的代码片段——我已经声明了 3 个函数(即 1 个传递一个 int 和其他传递对一个 int 的引用)。执行程序后,我发现调用函数(tripleByReference)后“count”变量的值没有改变以反映它的三元组(count 仍然等于 5)。然而,调用函数 (tripleByReferenceVoid) 会修改变量,但这是因为变量(计数)直接发生了变化。
我知道,通过引用传递,调用者使被调用函数能够直接访问调用者的数据并对其进行修改,但这无法通过将变量传递给函数(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
谢谢你。