我对C++参考参数有一些疑问。我从这个网站上学到:
http://www.doc.ic.ac.uk/~wjk/c++Intro/RobMillerL3.html第一个程序:
#include<iostream>
using namespace std;
int area(int length, int width);
int main()
{
int this_length, this_width;
cout << "Enter the length: ";
cin >> this_length;
cout << "Enter the width: ";
cin >> this_width;
cout << "\n";
cout << "The area of a " << this_length << "x" << this_width;
cout << " rectangle is " << area(this_length, this_width) << endl;
return 0;
}
int area(int length, int width)
{
int number;
number = length * width
return number;
}然后作者建议“在某些情况下,要求函数修改传递给它的实际参数的值是合法的”.After,他引入了新的函数:
void get_dimensions(int& length, int& width)
{
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "\n";
}当我们将值作为参数传递时,主要的优点是什么?
发布于 2015-07-07 16:59:23
通过引用传递的优势:
通过引用传递的缺点:
,
源
发布于 2015-07-07 17:23:44
已经有了一个很好的答案(imho值得接受)。但是,我想给出一个更基本的答案,因为您似乎是第一次遇到通过引用传递:
此函数:
void foo(int x){x +=1;}可以对传递的(通过值)参数的值做任何事情,但它没有机会向调用者返回任何东西,即x+=1实际上根本没有任何作用。
另一方面,这个函数:
void bar(int& x){x +=1;}不仅获取值,而且还处理作为参数(通过引用)传递的实际变量。因此,x+=1在函数之外也有作用。
这两个功能都在起作用:
int main(){
int a = 1;
foo(a); // foo gets a copy of a and increments its value
// a is still 1
bar(a); // bar directly increments the value of a
// a is now 2
}这是按引用传递参数(bar)与按值传递(foo)的主要区别。通过引用传递的主要优点是不需要复制参数值。(这是通过值传递通常是通过常量引用完成的。传递const引用类似于传递值,因为即使实际上传递了引用,该值也不能更改。)但是,有关更多详细信息,请参阅Rohits答案。
发布于 2015-07-07 17:35:35
int &a是对传递给该函数的任何参数的引用,您应该始终将引用视为变量的别名(它类似于const指针)。
如果您的引用不是const,则允许您进行更改,从而更改原始变量的内容。
它很有用,原因有很多。首先,它可以避免在通过引用传递参数时进行复制,从而提高性能。如果你有一个函数需要返回多个结果,它也很有用,例如:
int f (int &a,int &b,int &c,int&d);
int main
{
int first,second,third,result;
result = f(first,third,result);
} 所有int变量都可以在函数中更改。
https://stackoverflow.com/questions/31264027
复制相似问题