八-----函数探幽

八-----函数探幽

1. 引用

1.1 引用变量的主要用途是用做函数的形参。经过将引用变量用做参数,函数将使用原始数据而不是其副本
1.2 引用声明时必须初始化,引用更接近于 const 指针,一旦建立完毕,就会一直效忠算法

int & r = rain;
int *const p = &rain

1.3 注意使用常量引用来传递信息,防止函数修改数据函数

int function(const int &r);

1.4 返回引用以下:指针

structure & function(structure &r){
    //statement
    return r;
};

1.5 若是不但愿函数返回值被修改,则应添加 constcode

const structure & function(structure &r){
    //statement
    return r;
};

1.6 最重要!!! 返回引用时应注意避免返回临时变量或者局部变量的引用,不然程序会崩溃io

2. 函数重载

2.1 函数重载时,类型的引用和类型自己将被视为同一个参数(特征标)
2.2 函数模板能够重载,但事实上重载过程有局限性,很差实施function

template <typename T>
//or => template <class T>
void swap(T &a, T &b)
{
    T temp;
    temp = a;
    a = b;
    b = temb;
}

2.3 显示具体化技术
算法稍有不一样,可是特征标不变,没法使用重载,就得用此技术模板

template <> void swap<structure>(structure &, structure &)
template <> void swap(structure &, structure &)
相关文章
相关标签/搜索