八-----函数探幽

八-----函数探幽

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 如果不希望函数返回值被修改,则应添加 const

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

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

2. 函数重载

2.1 函数重载时,类型的引用和类型本身将被视为同一个参数(特征标)
2.2 函数模板可以重载,但事实上重载过程有局限性,不好实施

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 &)
posted @ 2018-10-16 14:56  JeffreyLee  阅读(162)  评论(0编辑  收藏  举报