//const和指针的关系
int a = 10, b = 20;
int* p1 = &a;
int const* p2 = &a;
const int* p2 = &a;
int* const p3 = &a;
const int* const p4 = &a;
我们可以知道 p1指向a的地址,通过 p1我们可以改变a的值,也可以将p1指向b的地,这就是我们通常所使用的指针。那么通过const修饰以后,就会有不同的限制。
int const* p2 = &a;
const int* p2 = &a;
这两条语句是相同的,我们在考虑const时,要看const对什么起了修饰作用 。比如这两条语句的const都是与 * 号结合。因此在const的修饰下,我们可以改变p2所指之物,但是不能改变p2所指之物的值。
int a = 10, b = 20;
int const* p2 = &a;
const int* p2 = &a;
*p2 = 20; //error
p2 = &b; //可以
反观这一条语句
int* const p3 = &a;
我们发现const与p3结合,所以const修饰的是p3。我们可以通过p3修改a的值,但是不可以修改p3的所指之物。
int a = 10, b = 20;
int *const p3 = &a;
*p3 = 20; //可以
p3 = &b; //error
同理可以得出
const int* const p4 = &a;
p4 = &b; //error
*p4 = 20; //error
那么问题来了:
int a = 10, b = 20;
const int* s = &a;
int* p1 = s;
int const* p2 = s;
int* const p3 = s;
const int* const p4 = s;
p1,p2,p3,p4,哪句可以编译,哪句不可以编译?
很明显p1,p3不可以编译。
我们的指针能力只能够缩小,并不可以扩大。
那么再看另一个问题:
int a = 10, b = 20;
int* const s = &a;
int* p1 = s;
int* const p2 = s;
int const * p3 = s;
int const* const p4 = s;
p1,p2,p3,p4,哪句可以编译,哪句不可以编译?(仔细想)
答案是都可以编译通过!
你们想对了吗?
解释如下:
但是有一种情况就会编译不通过:
const int a = 10;
int *p = &a; //error
const int *p = &a; //OK
我们可以想一想其中的理由。