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
捆到一起,大家都不要变啦
由于常量与指针联姻的方式不同形成了多种貌合神离的结晶:
常量指针、指向常量的指针、指向常量的常量指针
---------------------------------------------------------------
貌:
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
捆到一起,大家都不要变啦
相关文章推荐
- Item07. 常量与指针的联姻(Const Pointers and Pointers to Const)
- Item07. 常量与指针的联姻(Const Pointers and Pointers to Const)
- const Pointers and Pointer to const Objects 常量指针和指向常量对象的指针
- const Pointers and Pointer to const Objects 常量指针和指向常量对象的指针
- 常量指针(const pointer)和指向常量的指针(pointer to const)
- C语言拾遗:常量指针与指针常量(const int *ptr, int const *ptr, int * const ptr, const int * const ptr区别)
- 指向函数的指针(pointers to functions)和回调函数
- C++ Special:const关键字和常量指针 vs 指针常量
- 条款02:尽量以const, enum, inline替换#define(Prefer consts,enums, and inlines to #defines)
- C语言之const常量(摘自C和指针)
- c语言的指针、数组和常量修饰符const
- string 转 const char * 转 char * , 常量指针和指针常量
- 【指针常量】const int* p
- const常量、指向常量的指针和常量指针
- 数组和指针(Arrays and Pointers)
- 关于const常量与指针赋值的问题
- 常量指针(const*)和指针常量(*const)
- Member Function Pointers and the Fastest Possible C++ Delegates - 成员函数指针与高性能的C++委托
- 指针的指针(pointers to pointers)
- const,constexpr与指针,常量表达式