原链接:http://blog.youkuaiyun.com/tobacco5648/article/details/8530975
1.const指针是一种指针,此指针指向的地址是不能够改变的,但是其指向的对象是可以被修改的,其定义类似:
int* const p=地址;
比如下面的代码:
- int b=12;
- int* const a=&b;
- void tes()
- {
- *a=1;
- }
如果将代码修改为:
- int b=12;
- int* const a=&b;
- void tes()
- {
- int c=2;
- a=&c;
- }
t.cpp: In function 'void tes()':
t.cpp:6:5: error: assignment of read-only variable 'a'
因为指针a是const的,不能被重新赋值。
2.指向const对象的指针,其指向的对象是const的,不能被修改,但是其本身并不是const的,可以修改其指向的地址。
声明方式为:
const int *p;
- const int* a;
- void tes()
- {
- int c=2;
- a=&c;
- }
- const int* a;
- void tes()
- {
- int c=2;
- a=&c;
- *a=4;
- }
t.cpp: In function 'void tes()':
t.cpp:6:5: error: assignment of read-only location '* a'
因为a所指向的对象是const的,不能修改。
版权声明:本文为博主原创文章,未经博主允许不得转载。