C++的函数

C++的函数

1.函数调用的优化

Calling a function with parameters taken by value causes copies of the values to be made. This is a relatively inexpensive operation for fundamental types such as int, but if the parameter is of a large compound type, it may result on certain overhead.

调用函数对于基本类型来说,可以是很容易的,但对于,复合类型,可能会产生一些开销,因为我们把参量一个个传入,可能会花费一些客观的时间,这个本可以避免的。

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

可以优化为

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

当然,为了避免有关参量,可以这样

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

如果你决定使用指针,那么要这样

cout << pinjie(&a,&b) << endl;

string pinjie(string *a,string *b)
{
    cout << a << endl;
    return *a+' '+*b;
}

传递的不是字符串参量,而是字符串参量的地址,这个概念不要混淆。

2.inline函数

Calling a function generally causes a certain overhead (stacking arguments, jumps, etc…), and thus for very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function.

可以看出,函数调用可能会有些开销,对于一些小的函数,这种开销显然不值得的,所以可以用inline,将这函数代码直接编写到主函数中,而不是去执行相关函数的调用,这样类似于宏的设定则能避免调用函数所产生的开销,这种你是应该明确的。

3.Default values in parameters

在C++中,对于函数的参数可以使用默认值,但这在C中是不允许的,看个例子就能明白。


#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int  divv (int a,int b=2)
{
    return a/b;
}
int main()
{


    std::cout << divv(2) << endl;   
    std::cout << divv(10,5) << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值