就这几种。有啥不一样?
const int a;
int const b;
const int* a1;
int const* c1;
int* const
怎么理解上面的const?
一般情况下,可以把const 看作是用来修改变量类型的,比如
const int a
int 是类型,const是修饰int类型,可以理解为 这个int 类型是 const 的,也就是不可修改的
int const b
这个和
const int a
没区别
编译器会认为都一样
但是指针就有点特别,你得看*是跟在const前面,还是后面
const int* a1;
int const* c1;
上面这个两句,*在const后面,表明a1,c1是两个指针,*前面的const int,const int 表示这两个指针是指向const int类型,a1,c1这两个指针指向的变量内容不能被改变
int f =3;
int c = a;
const int* a1 = &f;
int const* c1 = &f;
*a1 = 1; //错
c1 = &c;//对
下面
int* const b
*在const前面,说明这个后面b是个const指针,指向一个int类型,这指针本身是不能改的,但内容可以改
int f =3;
int* const b1 = &f;
b1 = &c;//错
*b1 =2;//对
如果想让内容和变量本身都不能该
int f =3;
const int* const b1 = &f;
b1 = &c;//错
*b1 =2;//错
上面表明,b1是个const类型指针,指向了一个const int类型,所以内容和指针都不能改
差球不多就这几种,
还有,在VS里,const写多少,都没有关系。
它会忽略没用的const
const const int* const const b1 = &f;
以上代码,最终解释为
const int* const b1