- 引用
- 引用的定义
- 引用注意事项
- 引用做函数返回值
- 引用的实质
- 常量引用
- 引用与指针的区别
- 函数重载
- 函数默认参数与占位参数
- 函数重载定义
- 重载函数的注意事项
语法格式:类型名 &外号 = 变量名;
1 引用的实质是对一个内存空间起别名
2 引用的东西与原来的东西就是完全一样的东西。不管是变量对应的值,还是地址,还是地址的偏移量,都是一样的。
1 引用必须初始化
2 引用在初始化后,不可以改变
#includeusing namespace std; void mySwap03(int& a, int& b){ //使用引用交换 int temp = a; a = b; b = temp; } int main() { int a = 10; int &b = a; //引用必须初始化 且初始化后不能改变 cout << "a = " << a << endl; cout << "b = " << b << endl; int c = 20; b = c; // //这是赋值操作,不是更改引用 同时把a和b都改为10 cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; int d = 50; int e = 10; cout << "d = " << d << "e = " << e << endl; mySwap03(d,e); cout << "d = " << d << " e = " << e << endl; }
通过引用参数产生的效果同按地址传递是一样的。引用的语法更清楚简单
引用做函数返回值1 引用是可以作为函数的返回值存在的
2 不要返回局部变量引用
3 函数调用可以作为左值
#include引用的实质using namespace std; 返回静态变量引用 int& test() { static int a = 20;//加static使之成为静态变量 return a; } int main() { // int& ref = test0();//不能返回局部变量的引用 int& ref = test(); cout << "ref =" << ref << endl; test() = 1000; // //这就相当于让a = 1000 cout << "ref = " << ref << endl; return 0; } ~
本质:引用的本质在c++内部实现是一个指针常量.
int& ref = a;
自动转换为 int* const ref = &a; 指针常量是指针指向不可改,也说明为什么引用不可更改
ref = 20;
自动帮我们转换为: *ref = 20;
常量引用主要用来修饰形参,防止误操作
在函数形参列表中,可以加const修饰形参,防止形参改变实参
#include引用与指针的区别using namespace std; void show(const int &val)//避免传入的值被改 { // val = 100; 防止误操作 cout << val << endl; } int main() { int a = 10; int &ref = a; const int &ref2 = 10;//引用必须要一块合法的内存空间 加const // 编译器将代码修改为 int temp = 10; const int &ref2 = temp; cout << ref << " " << ref2 << endl; int val = 10; show(val); return 0; }
1 引用必须初始化 指针不必初始化
2 引用初始化后不能改变 但是指针可以改变所指的对象
3 不存在控制的引用 但是存在空值的指针
函数默认参数:在C++中,函数的形参列表中的形参是可以有默认值的。如果我们传入了值就用传入值 没有就使用默认值
函数占位参数:C++中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置 (占位参数也可以有默认参数)
#include函数重载定义using namespace std; int add(int a,int b=10,int c=20)// 如果我们传入了值就用传入值 没有就使用默认值 { return a+b+c; } void print(int sum,int ) { cout << "sum = " << sum << endl; } int main() { int a = 1; int sum = add(a); print(sum,10);//占位参数必须填补 } ~
函数重载是一种特殊情况,C++允许在同一作用域中声明几个类似的同名函数,这些同名函数的形参列表(参数个数,类型,顺序)必须不同,常用来处理实现功能类似数据类型不同的问题。
函数重载满足条件:
同一个作用域下
函数名称相同
函数参数类型不同 或者 个数不同 或者 顺序不同
注意 函数的返回值不可以作为函数重载的条件
#include重载函数的注意事项using namespace std; void func() { cout << "func() 的调用" << endl; } void func(int a) { cout << "func(int a) 的调用" << endl; } void func(int a,double b) { cout << "func(int a,double b) 的调用" << endl; } void func(double a,int b) { cout << "func(double a,int b) 的调用" << endl; } //函数的返回值不可以作为函数重载的条件 int main() { func(); func(1); func(1,1.02); func(1.02,1); return 0; }
1 引用作为重载条件
2 函数重载碰到函数默认参数(避免二义)
#includeusing namespace std; void func(int& a)//变量 { cout << "func(int& a)的调用" << endl; } void func(const int& a)//常量 { cout << "func(const int& a)的调用" << endl; } void func2(int a,int = 10) { cout << "func(int a,int = 10)的调用" << endl; } void func2(int a) { cout << "func(int a)的调用" << endl; } int main() { int a = 10; func(a); func(10);//调用"func(int& a)"不合法 所以进入第二个 // func2(10);//碰到默认参数产生歧义,需要避免 }



