您的位置:首页 > 其它

Item07. 常量与指针的联姻(Const Pointers and Pointers to Const)

2005-04-09 11:27 302 查看
Item07. Const Pointers and Pointers to Const

由于常量与指针联姻的方式不同形成了多种貌合神离的结晶:
常量指针、指向常量的指针、指向常量的常量指针

---------------------------------------------------------------
貌:
1、差别:由const与*的位置决定
T *const cpt = pt; // const ptr to T 常量指针
T const *pct = pt; // ptr to const T 指向常量的指针
2、读法:自右向左
3、T const *pct = pt; 与 const T *pct = pt;是一个东西

神:
到底谁是const?
Const Pointers: 指针是const的,不可以再指向别的对象,但指向的对象值是可变的
Pointers to Const: 指向的对象是const的,可以指向别的对象,但指向的对象值是不能变的

----------------------------------------------------------------
Q:
1、Const Pointers与non-const Pointers的转换问题
non-const Pointers可以隐式转换成Const Pointers(例如作为函数的参数传递)。
反之则需要显示强制转换(若Const Pointers指向的对象也是个常量,转换为non-const

Pointers则会破坏其指向的对象的const属性,因此最好用const_cast显示的转换)
看来无中生有简单,要由有及无还要麻烦一点。
2、Const Pointers to Const
捆到一起,大家都不要变啦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: