c++ const引用 和 引用数组总结


const 引用,又叫常引用,引用的本质是指针,所以很多东西都是相通的.

const 和 数据类型可以交换

下面代码 int const 和 const int作用一样

 int a = 1;
 int const &ref = a;    
 const int &ref = a; 

跟指针一样,const修饰的是右边的变量

int const 和 const int可以交换,所以修饰的是int,表示int是不能改变的

 	int a = 1;
    int const &ref = a;
//    ref = 10;//错误,常引用不能修改值
    
    const int &ref2 = a; //const int 等价于 int const,因为const 和数据类型可以交换
//    ref2 = 20;

常引用可以指向常量,当做常量使用

作用可以看做是 swift中的let width = 100
如下

    int const &ref3 = 30; //当做常量使用,因为30是不能改变的,所以 常引用 ref3可以指向30
    cout << ref3 <<endl;

常引用 指向 表达式

常引用右边可以是个表达式,例如一个函数,函数返回值需要是常量const

int sum(){
    return 10;
}
void main(int argc, const char * argv[]) {
    const int &ref4 = sum();//因为sum的返回值是常量,所以用常引用可以使用
}

常引用作为函数形参可以接收 const类型 和 非 const类型,常引用 和 非const引用可以构成函数重载

int sum2(const int &a,const int &b){
   cout<< " sum2(const int &a,const int &b)"<< endl;
   return a + b;
}
int sum2( int &a,int &b){
   cout<< "sum2( nt &a,int &b)"<< endl;
   return a + b;
}

void main(int argc, const char * argv[]) {  
   int result = sum2(10,20);
   int a1 = 1;
   int a2 = 2;
   int result2 = sum2(a1, a2);//a1,a2都是变量,但是可以可以传给 const 形参函数
}

运行结果:
sum2(const int &a,const int &b)
sum2( nt &a,int &b)

指针形参的const和非const也能构成重载,跟const 引用一样

void sum3(const int *p1, const int *p2){
    cout << "sum3(const int *p1, const int *p2)" <<endl;
}
void sum3( int *p1,  int *p2){
    cout << " sum3( int *p1,  int *p2)" <<endl;
}
void main(int argc, const char * argv[]) {   
    sum3(&a1, &a2);
    const int *p1 = &a1;
    const int *p2 = &a2;
    sum3(p1, p2);
}

普通的形参变量 const和 非const 无法构成重载

void sum4( int a,  int b){
    cout << " sum4( int a,  int b)" <<endl;
}

//但是普通的形参变量 const和 非const 无法构成重载
void sum4( const int a,const  int b){
    cout << " sum4( int a,  int b)" <<endl;
}
//这里会报错:Redefinition of 'sum4' 表示重定义了sum4,因为2个sum4不能重载 
 

引用数组的2种格式:

  • int (&ref1)[3] = arr;
  • int * const &ref2 = arr;
  int arr[] = {1,2,3};
    //数组的引用格式1
    int  (&ref1)[3] = arr;
    ref1[0] = 10;
    

    //数组的引用格式2,因为数组名也是数组地址,数组是常量 ,arr 数组名,是数组的地址,
    //类型是 int * ,加上常量限制就是 int * const ,再创建引用,就变成了 int * const &ref = arr
    int * const &ref2 = arr;
    ref2[1] = 20;
    
    for (int i = 0 ;i < 3 ; i++){
        cout<< arr[i] << endl;
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值