关于const和指针

首先:const 放在类型前后是等价,习惯写于类型前面

例:const int a = int const a;

        const int *a = int const * a;

        int * const a = const (int *) a;     注:此时int * 通常用typedef替换 typedef int * ip;则const (int*) a = const ip a;


指向const对象的指针

1.const int *a 可以读作:a指向int型的const对象。指针a本身可以变,即可以指向其他const整型,但是其指向的int变量的值是不能变的,即任何对*a的赋值都是不合法的;

2.const int a=3;

    int *b=&a;

    不合法。要指向一个type类型的const对象,指针必须声明为const type * pointer型,没有const则不合法,因为那样只看指针的话是可以通过指针改变其指向的对象的值的;

3.int a=3;

   const int *b=&a;

   合法。允许将一个普通变量的地址赋给一个指向同类型const对象的指针,此时意味着不能通过指针来改变a的值,但可以直接修改a的值,若a=4,则a=*b=4,可以认为此时b自    以为自己指向const对象。指向const的指针也是经常用做函数的形参,防止实参在函数在被修改。


const指针

1.int *const a可以读作:a是const型的指向int型对象的指针。a本身是const类型的,即其初始化之后就不能再指向其他的对象,必须在定义同时完成初始化。

2.const int *const p是指p是一个const指针,而且指向的int型变量也是const的。

 

总结,可概括为,const在*的哪边,就是修饰的*哪边的东西(指针或对象)

 

const与typedef

例:

typedef string * str;

const str pstr;

此时const str pstr不等价于const string * pstr,而是等于const (string *) pstr = string * const pstr (注:const放在类型前后等价),

也就是说,pstr应该是一个const指针,指向的是string类型,

而const string * pstr的意思是pstr是一个指向string类型const对象的指针。

指针在定义时可将将 Type* 看成一种新类型,Type  *a=Type*  a=(Type*) a(但const Type * a不等于const (Type *) a,因为const修饰的类型不同,详见开头),

如此 typedef string *str = typedef (string*) str,const str pstr = const (string *) pstr = string * const pstr。


 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值