C++ Primer Plus读书笔记(八)函数探幽

1、内联函数

inline int square(x) {return x*x}

2、引用变量

  int& 中的& 不是地址运算符,就想定义指针时的char* 一样,int&指的是指向int的引用。

int rate;
int & res = rate;

这样使用res 做参数时,按址传递而不再是按值传递。

引用与指针的区别在于,引用在声明的时候必须进行初始化,而不能像指针那样先指向NULL,再进行初始化。

将引用初始化之后就不能修改引用的对象了,看个例子

int a = 5;
int & b = a;
int c = 10;

//如果这么做了
b = c;

//相当于把c赋值给a和b
a = c;
b = c;

3、默认参数

默认参数依赖于函数声明,用法如下

//just jugelizi
int func(const char * name, int length = 10);

又默认值的参数,添加默认值时必须从右向左。参数设置默认值之后,函数调用时就可以不传入对应参数,例如上边的函数可以这么用:

char * name = "hehe";
func(name, 3);
//or
func(name);

4、函数重载

定义相同函数名称,不同函数参数,即为函数重载。有几个特殊情况需要注意下:

int func(int num);
int func(int & num);
//这不是重载

int func(int num);
int func(const int num);
//const参数传两个函数都可以,但是非const参数只能传第一个

5、函数模板

  关键字 template 标准用法如下:

template <typename AnyType>
//template <class AntType> use class //写个交换函数 void swap(AnyType &a, AnyType &b) { AnyType temp; temp = a; a = b; b = temp; }

  当然了,模板函数也是支持重载的,举个栗子

template <typename T>    //original template
void swap(T &a, T &b);

template <typename T>    //Is need? of course. The new template
void swap(T *a, T *b, int n);
原文地址:https://www.cnblogs.com/gaoshaonian/p/12469159.html