const

const int *p;
// p 可变,p 指向的对象不可变
int const *p;
// p 可变,p 指向的对象不可变
int *const p;
// p 不可变,p 指向的对象可变
const int *const p; //指针 p 和 p 指向的对象都不可变
在平时的授课中发现学生很难记住这几种情况。这里给出一个记忆和理解的方法:
先忽略类型名(编译器解析的时候也是忽略类型名)
,我们看 const 离哪个近。
“近水楼
台先得月”
,离谁近就修饰谁。
const int *p;
//const 修饰*p,p 是指针,*p 是指针指向的对象,不可变
int const *p;
//const 修饰*p,p 是指针,*p 是指针指向的对象,不可变
int *const p;
//const 修饰 p,p 不可变,p 指向的对象可变
const int *const p; //前一个 const 修饰*p,后一个 const 修饰 p,指针 p 和 p 指向的对象
都不可变

posted @ 2014-04-20 12:39  jvava  阅读(105)  评论(0编辑  收藏  举报