前言
很容易弄混,记一下好了
总结
- int const * p等价于 const int *p 都是正常指针指向常量,可以修改指针(指向),不能修改指向的东西的值(指向的东西是const)
- int* const p 首先是const p 常量的指针,所以指向不能修改,但是指向的东西是可以改的
- int const * const p ==const int const * p 指针是常量 指向的也是常量 指针本身不能修改,指向的东西也不能修改
- 首先很推荐左边的写法,就是后置const,原来我不理解,后面发现标准库里都是这么写的,现在理解了,确实该这么写,因为类型很明确
- 按照左边的写法,*右侧的const(p左侧最近的const)限制的是p的类型 *左侧的const则限制的是指向的东西是否const.很清晰呢!
实验代码
int main( int argc, const char** argv )
{
int normalInt1 = 1;
int normalInt2 = 2;
//无修饰指针(p) 指向的类型是 常量的整型(int const)
int const* p_ci = &normalInt1;
//修改指针 √
p_ci = &normalInt2;
//修改指针指向的值 ×
// ( *p_ci ) = 3; // Read-only variable is not assignable
//常量的指针(const p) 指向的类型是 正常的整形(int)
int* const cp_i = &normalInt1;
//修改指针 ×
// cp_i = &normalInt2; // Cannot assign to variable 'cpi' with const-qualified type 'int *const'
//修改指针指向的值 √
( *cp_i ) = 3;
//常量的指针(const p) 指向的类型是 常量的数值(const int).
int const* const cp_ci = &normalInt1;
//修改指针 ×
// cp_ci = &normalInt2; // Cannot assign to variable 'cp_ci' with const-qualified type 'const int *const'
//修改指针指向的值 ×
// ( *cp_ci ) = 3; // Read-only variable is not assignable
return 0;
}