内联函数
提高运行效率,但是占用了更多的内存。
一般的函数调用是将进入到对应的函数代码块,而内联函数是直接在代码段中插入函数的拷贝。
inline int func(int a,double b);
...
inline int func(int a,double b)
{
...
}
在C语言中,可以使用#define进行操作。
引用变量
声明引用时,必须进行初始化,表明为何变量的引用。
int a;
int &b=a;
a为int变量,b为int的引用。a和b指向相同的值和内存单元。
当引用作为函数的参数时,在函数内,可以直接对原变量进行操作,而不是操作其拷贝。如果要避免引用的特性影响,可以考虑使用const对变量进行修饰。
在函数中使用引用变量传递数据可以显著提高效率,节省时间与内存。
在引用作为返回值时,函数不能返回一个内存已经被清理的引用。
函数的默认参数
对函数的参数进行默认赋值:
必须通过函数原型。
int func(int a,int b=0);
...
int func(int a,int b)
{
...
}
函数重载(多态)
主要的判别依据为函数的参数列表(函数特征标),C++内可以定义名称相同的函数,但必须是特征标不同的。而函数类型不能作为重载的依据。
int func(int a,int b)
int func(int a,double b)
long func(int a,int b) //invalid
如果可以重载多个函数,符合多个函数的定义,将调用最为匹配的版本。在使用过程中,可以直接当成多个函数进行声明/定义。
函数模板
如果需要多个将同一种算法用于不同类型的函数时,可以选用模板函数。
//function protype
template <typename T>//or class T ,T means type
void func(T a,T b);
...
template <typename T>
void func(T a,T b)
{
...
}
函数模板具体化及实例化
函数模板有时无法处理某些特殊类型的数据,此时需要为特殊类型提供具体化的模板定义。**显示具体化(specialization)**需要重写编写相关的函数定义。
//template function protype
template<class T>
void swap(T a,T b);
//explicit specializaion for double tyoe
template <> void swap<double>(double a,double b);
template <> void swap(double a,double b); //simpily form
#include<iostream>
#include<cstring>
using namespace std;
template <typename T>
T func(T temp[],int a);
//具体化方法
template <> char *func<char*>(char* temp[],int a);
int main()
{
int a[6]={5,6,2,3,1,3};
float b[4]={2.1,3.2,4.3,5.6};
char* q[4]={"hhaha","hiahiaok","ko whta","nuaksda"}; //使用q[4][20]会出错
cout<<func(a,6)<<endl;
cout<<func(b,4)<<endl;
cout<<func(q,4)<<endl;
}
template <typename T>
T func(T temp[],int a)
{
T max=temp[0];
for(int i=0;i<a;i++)
{
if(max<temp[i])
{
max=temp[i];
}
}
return max;
}
//需要自己重新编写定义
template <> char *func<char*>(char* temp[],int a)
{
char *max=temp[0];
for(int i=0;i<a;i++)
{
if(strlen(max)<strlen(temp[i]))
{
max=temp[i];
}
}
return max;
}
实例化(instantiation)是指,程序根据函数模板来自动生成某种数据类型的函数。有隐式实例化和显式实例化两种。
隐式实例化,显式实例化,与显示具体化统称为具体化。
//template function protype
template<class T>
void swap(T a,T b);
template void swap<char>(char &,char &); //explict instantiation
...
short a,b;
swap(a,b) //implicit instantiation
函数的选择:(此处不再展开介绍)
非模板函数>模板函数,
模板函数中,显式实例化>隐式实例化。