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

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型等数值时并无大碍,但是当参数是一个复杂的混合数据类型。例如:


3
4
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;
}









  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值