C++ const对象指针与const指针 (八)

(1)例:1.   int i=1;
               const int *cptr=&i;
               *cptr=2;                //出错,cptr指向的是常量1
                cout<<*cptr<<endl;             //
         2.    int i=1;
                 const int *cptr=&i;
                 i=2;                //正常
               cout<<*cptr<<endl; //输出2
         3.   int i=1,tt=8;
                const int *cptr=&i;
                cptr=&tt;                //正常
               cout<<*cptr<<endl; //输出8
          综上:const pointer导致的唯一结果是不能用 *cptr=..,其他均可  (cptr本身可以更改,而其指向不可改)
          但上面程序没意义,const pointer指向的应该也是const int...
          const int a=1;
          const int *cptr=&a  或  const void *cptr=&a;          //常量,指针也必为常量
注意: 指向 const 的指针常用作函数的形参。将形参定义为指向 const 的指针,确保传递给函数的实际对象在函数中不因形参而被修改。

(2)const Pointer本身值不可改,但其指向的是否可改是根据指向的对象是否为const。
              int i=10,tt=88;                  //若为const int i=10;也出错
              int *const cptr=&i;
              *cptr=9;                          //可以
              cptr=&tt;                         //出错
              cout<<*cptr<<endl;         
(3)const Pointer to a const Object  指针本身与其指向的对象均不可以改.
              const int i=10;
              const int *const cptr=&i;

总结:有加const的话,都是从右往左看的,即左边修饰右边的。
        例:const int *cptr                  cptr是个int型指针, 这个int是常量
               int *const cptr                 cptr(即指针)是const型,这个const是指向int的
               const int *const cptr=&i;   cptr是const型, 而第2个const是指向int的,而这个int是常量

             原变量:int型    -->    指针变量 int *const p ,   const int *,    const int *const pI=&a;
                   const int型 -->    指针变量const int *p,   const int *const pI=&a;

     附加:
           1        const string str;
                     string const str;  //两者一样
           2        string s;
                     typedef string *pstring;
                     const pstring cstr1 = &s;    //1种
                     pstring const cstr2 = &s; //   2种all three decreations are the same type
                     string *const cstr3 = &s; // they're all const pointers to string                    

             (书写时一般把const放于前面,但声明时建议const置于后面,便于理解)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值