第8章 函数探幽

1. 引用的本质

int a = 1;
int& copy = a;
//实际是:指针常量
int* const copy = &a; 

引用一旦指定后,就不能再作为其他变量的引用

2. 关于const和引用

非引用--无返回||引用-无返回类似

//1.可行
void test(int a);
int a = 1;
test(a);

//2.可行
void test(const int a);
int a = 1;
test(a);

//3.可行
void test(const int a);
const int a = 1;
test(a);

//4.可行
void test(int a);
const int a = 1;
test(a);

引用-有返回

//1.可行
int& test(int& a){
    return a;
}
int a = 1;
int& temp = test(a);

//2.可行
const int& test(int& a){
    return a;
}
int a = 1;
const int& temp = test(a);

//3.可行
const int& test(const int& a){
    return a;
}
int a = 1;
const int& temp = test(a);

//4.不可行
int& test(const int& a){
    return a;
}
int a = 1;
int& temp = test(a);

另外,引用返回值传递给非引用是,以值传递的方式进行传递

 3. 默认参数

默认参数,必须从右向左添加默认值

4. 函数重载

1. 如传入参数在重载版本中不存在,则发生错误

2. 引用和类型本身,不能同时出现。如:void test1(int a);  void test1(int&a);

3. 入口参数相同,但返回值不同,是错误的,不能发生函数重载。

5. 函数模板

1.typename 和 class 都可以用于模板声明

2. 函数模板 也可以发生重载。

3. 显式具体化模板:

//模板函数
template<class T>
void swap(T& a,T& b){
    T temp = a;
    a = b;
    b = temp;
}

template<> void swap(int &a,int& b)
//对于非int类型调用 模板函数
//对于int数据调用 显示具体化函数

4. 显示实例化

对于模板发生重载时,C++需要进行重载解析;

一般首先选择更为具体的函数进行调用。

函数入口参数、

无const引用和const引用,优先选择自己相同类型

猜你喜欢

转载自blog.csdn.net/qq_42813620/article/details/130608390