对int * const p=&i, int const * p=&i与int const * const p=&i的理解
对int * const p=&i, int const * p=&i与int const * const p=&i的理解,指针常量,指向常量的指针与指向常量的指针常量
一:首先这里指明const的用法:
const 常量类型 常量名=常量表达式;
例如:
1. const double PI=3.14;//常量
2. const char str[]="Hello world!" //常数组
@值得注意的一点是,const在定义常量时必须要在定义时初始化;
例如:
#include <iostream>
using namespace std;
int main()
{
const int n;//error
const int n=9;//right
cout<<"n="<<n<<endl;
n=n+8;//error,因为n为常量,不可修改;
cout<<"n="<<n<<endl;
return 0;
}
二、const用于上述的直接定义常量时,定义之后的常量名的值是无法改变的。但是可以通过引用和指针来改变:
1、引用:
#include <iostream>
using namespace std;
int main()
{
int x=5;
const int &rx=x;
x=7;//rx=7错误
cout<<rx;
}
结果为 7
因为定义rx为常量,所以不能直接改变rx的值,
但是可以通过改变x的值来改变rx的值。
2.指针:
下面通过例子来说明const在指针中的用法,来完成对int * const p=&i, int const * p=&i与int const * const p=&i的理解的回答。
#include <iostream>
using namespace std;
main()
{
int i=4,j=7;
int* const p=&i;
cout<<*p<<endl;
i=j;
cout<<*p<<endl;
p=&j;//error!!!
cout<<*p<<endl;
}
因为p为指针,且const 又定义了p为常量,p中存储着i的地址,不能修改,但是该地址所指向的存储空间中值的修改是允许的。
#include <iostream>
using namespace std;
int main()
{
int i=7;
int *const p=&i;
i=3;
cout<<*p<<endl;
*p=34;
cout<<*p<<endl;
cout<<i<<endl;
}
结果:
3
34
34
综上可知,对于int * const p=&i,p的值不能改变,但是*p的值可以随意改变。
#include <iostream>
using namespace std;
int main()
{
int i=7,j=9;
int const *p=&i;
i=3;// *p=j;error
cout<<*p<<endl;
p=&j;
cout<<*p<<endl;
}
结果:
3
9
因为int const p=&i;定义p为常量,所以不能直接对*p赋值,但是可以改变 i 的值,或者改变p的值!!!
#include <iostream>
using namespace std;
int main()
{
int i=7,j=9;
int const *const p=&i;
i=3;
p=&j;//error
*p=12; //error
cout<<*p<<endl;
}
因为int const * const p=&i对*p定义为常量,对p也定义为常量。所以不能对 *p修改也不能对p修改!!!