常量指针和指向常量的指针

最近读c++ primer,学了指针和常量的复合使用,在百度的面试里也见过

1.常量指针(const point)

即指针本身是个常量,指向的地址不变

const离变量更近,相比于*,从右往左读

int * const p顶层const(本身不变)

2.指向常量的指针(point to const)

即指针指向的对象,是个“常量”(这里的意思,不能通过指针修改所指对象的值,但能通过其他方式修改)

*离变量更近,相比于const,从右往左读

int const * p,底层const(本身可变,指向对象不变)

3.举例

#include<iostream>
using namespace std;
int main(){
    int a[2]={1,2};
    const int *p_t_c=&a[0];
    int * const cp=&a[0];
    cout<<a[0]<<endl; //1 
    cout<<*p_t_c<<endl; //1
    cout<<*cp<<endl;  //1
//    cp = cp+1; // 此处错误,不能修改
//    cout<<*cp<<endl; 
    p_t_c += 1; // 可以修改
    cout<<*p_t_c<<endl; //2
    
    *cp = -1;
    cout<<*cp<<endl;
//    *p_t_c = -2; //错误,不能修改
    a[1] = 3; //可以通过其他方式修改 p_t_c指向对象的值
    cout<<*p_t_c<<endl; //3
    
    return 0;
}

4.判断

从右往左读,看*和const的位置关系

遇到p就替换成“p is a ”遇到*就替换成“point to”。

const int p; // 常量
const int* p; // p is a point to  int const
int const* p; // p is a point to  const int 
int * const p;// p is a const point to int 
const int * const p;// p is a const point to int const 
int const * const p;// p is a const point to int const 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值