[英]C++ references and references parameters
请查看下面的代码片段-我声明了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
谢谢。
tripleByReference
不会更改count
的值,因为您从不会分配它。 您正在返回值。
tripleByReferenceVoid
是不同的。 您正在分配它( count *= ...
),这就是为什么这些更改会得到反映的原因。
在函数tripleByReference
您甚至没有尝试修改count
的值,而在函数tripleByReferenceVoid
您显式地修改了count
。 因此产生了明显的预期效果:后一个函数修改了count
,前一个函数没有。 也就是说,这些功能仅执行您明确地并有意识地要求它们执行的操作。
像这样的问题很难回答,因为几乎不可能理解是什么使您提出的。 这两个功能的行为是不同的,您似乎对此感到困惑。 但是,当您自己明确地写出它们在特定方面有所不同时,为什么您会感到困惑呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.