C++参数传递的效率思考

来源:互联网 发布:上海哪里有美工培训 编辑:程序博客网 时间:2024/06/16 03:53
C++中对函数定义,传递参数的方法,直接传递值或者传递参考值。首先直接传递值例如:
#include <iostream>using namespace std;int addition (int a, int b){  int r;  r=a+b;  return r;}int main (){  int z;
  int x = 5, y = 3;  z = addition (x,y);  cout << "The result is " << z;}

输出结果为8

在这种传递方式下,x,y的值经过函数处理后是不会改变的。即:

#include <iostream>using namespace std;void duplicate (int a, int b, int c){  a*=2;  b*=2;  c*=2;}int main (){  int x=1, y=3, z=7;  duplicate (x, y, z);  cout << "x=" << x << ", y=" << y << ", z=" << z;  return 0;}

这样输出x,y,z的结果,仍旧是1,3,7

若要调用duplicate函数成功,应用reference的方式传递参数。

#include <iostream>using namespace std;void duplicate (int& a, int& b, int& c){  a*=2;  b*=2;  c*=2;}int main (){  int x=1, y=3, z=7;  duplicate (x, y, z);  cout << "x=" << x << ", y=" << y << ", z=" << z;  return 0;}
这样输出的结果就是 2,6,14了。

通过之前value的方式在传递参数时,当只是int型等数值时并无大碍,但是当参数是一个复杂的混合数据类型。例如:

34
string concatenate (string a, string b){  return a+b;}
两个字符串再这样传递参数则,则对调用函数产生了大量的数据处理,这样效率是很低的。而是用reference的方法传递参数则不会有这种情况,相对更加高效。例如:

string concatenate (string& a, string& b){  return a+b;}

但是这样也会产生问题,a,b的值可能会因为调用函数改变了原本的值,那这样怎么处理呢?

直接上代码:

string concatenate (const string& a, const string& b){  return a+b;}









0 0