Reference(引用)

Reference(引用)

  • 什么是引用(Reference)
int main(){
int age =10;

int &ref= age;//引用,ref是引用变量,引用了age
ref = 20;//类似于起别名

// int *p = &age;//通过指针间接修改
// *p =20;
std::cout<<age<<std::endl;
getchar();
return 0;
}

引用需要在定义时就需要初始化

  • 不可以重新指向
  • 以后相当于被引用只不过换个皮而已

引用使用实例

void swap(int &v1,int &v2){
//交换数字数值函数
int temp = v1;
v1=v2;
v2=temp;

}

//使用指针实现swap
void swapByPtr(int *v1,int *v2){
int temp = *v1;
*v1=*v2;
*v2=temp;

}

int main(){
    int a = 11,b=22;

swap(a,b);//引用方法调用
std::cout<<"引用方法调用\n"<<"a=:【"<<a<<"】,b=:【"<<b<<"】\n"<<std::endl;
swapByPtr(&a,&b);//指针方法调用
std::cout<<"指针方法调用\n"<<"a=:【"<<a<<"】,b=:【"<<b<<"】\n"<<std::endl;


}

引用的本质其实就是--->(削弱的指针)

  • 引用可以被const修饰,然后就无法通过引用修改数据,可以成为常引用
const int &a= v;//常引用,不可修改

  • const意义
    • 安全:将某个空间的东西变成只读;
骚操作
int a=10;
const int &b=a;//b是对a的引用,也就是b内容一个int类型的10;但是a不是const类型啊
a=100;
std::cout<<b;//脱裤子放屁,而且用指针也可以做到;
int *p=&a;
*p=10086;
std::cout<<b;

  • 看个好玩的
int age= 10;
int & const ref= age;
ref=300;//可以操作!
//类似 int * const p = age;不能用p但是可以用*p

所以得出结论

const 必须写在 &符号左边才算常引用


-------------------------------再来看个好玩的-----------------------------------

int  age =10;
int a,b;

int const &ref = a+b; 
  • 同样,直接用const修饰的常引用也可以直接等于一个函数返回值
int testFunction(){
return 12138//此函数直接return一个数字
}

int main(){

    const int &ref = testFunction();
}

特点

1.可以指向临时数据【常量、表达式、函数返回值等等】
2.指向不同类型的数据 {const int &ref = int age;}
3.作为函数参数是,可以接受const和非const实参(只限于使用const修饰过的形式参数)
可以跟非const引用构成重载
适用于const指针 const int *ptr做形参

举个栗子;

//创建一个函数,形参采用引用方式,在调用时我们直接传递变量
int test(int &a,int &b){
    return a+b;
}

int main(){

    int q,w;
    q=1;w=1;
    return test(q,w);
}
  • 这样操作是可以的,但是如果我把return test(q,w)替换成 return test(10,23)这样就会报错
    因为int &ref = 12;是不合法的
    但我们可以通过const修饰来做到
int test(const int &a,const int &b){
    return a+b;
}

int main(){

    
    return test(123,213);
}
int func(int &ref,int &ref2){

}
int func(const int &ref,const int &ref2){

    
}//这两个函数可以构成重载

当常引用指向了,不同类型的数据时会产生临时变量相当于换了个变量指 🤣


数组引用

补充一点概念
1.数组名其实是数组的地址 也是数组首元素的地址
2.数组名可以看作是指向数组首元素的指针!(*) 但是其地址是一个常量

int arr[]={1,2,3,};
int *  const &ref = arr;
posted @ 2024-03-12 11:59  dxwxb  阅读(61)  评论(0)    收藏  举报