引用:
int& t1(){
int a = 10;// 局部变量 存放在四区中的 栈区
return a;
}
int main(){
int &ans = t1();
cout<<" ans = "<< ans<<endl;//编译器会做保留
cout<<" ans = "<< ans<<endl;
return 0;
}
两次输出的结果分别是什么?
//函数调用可以作为左值
int& t1(){
static int a = 10;// 存放在全局区,程序全部结束后释放
return a;
}
int main(){
int &ans = t1();
cout<<" ans = "<< ans<<endl;
cout<<" ans = "<< ans<<endl;
t1() = 11111; //左值
cout<<" ans = "<<ans<<endl;
return 0;
}
两次输出的结果是?
引用的本质:指针常量
int * const ref = &a;
注意:引用一旦初始化,就不可以发生改变
//常量引用
//使用场景:修饰形参,防止误操作
//int & ref = 10;//引用必须引一块合法的内存空间
int a = 10;
const int & ref = a; //加入const ,变为只读,不可修改
//调用函数
void f(const int & ref){
//ref = 7987898;//ref只能用来接收参数,无法进行修改,实现了防止误操作
.....
}
函数默认参数
注:
1、如果函数形参的某个位置已经有了默认参数,那么从这个位置开始往后,都必须有默认值
int f(int a=10,int b ){//会报错,b也得有默认值
...
}
2、函数的声明和实现 只能有一个有默认值(二义性)
函数占位参数
int fun(int ,int){...}
//占位参数可以有默认参数
int fun2(int , int = 10){...}
函数重载
条件:
1、同一个作用域
2、函数名相同
3、函数参数类型不同,或者个数不同,或者顺序不同
注:函数的返回值不可以做为函数重载的条件
//引用作为重载条件
void f(int & a){...}
void f(const int & a){...}
int main(){
int a = 10;
f(a);//调用(int & a)
f(10);//调用(const int & a)
}
//函数重载遇到默认参数
void f(int a,int b = 10){...}
void f(int a){...}
int main(){
f(10);//报错。二义性
}