一个指针可以分成两部分来看,那个*为实际存储的内容(*pointer),变量名为那个地址。就是一个指针分成地址和内容两部分。
那么用常量修饰指针,要看修饰的是那个部分,离哪个近就是修饰哪个,哪个就改不了。
两个都修饰的,两个都改不了。
上代码:
//__________________常量指针__________________
int HoursInDay=24;
int const * pInteger=&HoursInDay;//当用一个const修饰一个指针,那么这个指针将不能用*p修改值
cout<<"pInteger24:"<<pInteger<<endl;
cout<<"*pInteger24="<<*pInteger<<endl;
int MonthsInYear=12;
pInteger=&MonthsInYear;
cout<<"pInteger12="<<pInteger<<endl;
cout<<"*pInteger12="<<*pInteger<<endl;
cout<<"HoursInDay="<<HoursInDay<<endl;
// *pInteger=13;//不可以
int const * pAnotherPointerToInt=pInteger;//必须完全一样的修饰词才能赋值
cout<<"pAnotherPointerToInt="<<pAnotherPointerToInt<<endl;
cout<<"*pAnotherPointerToInt="<<*pAnotherPointerToInt<<endl;
//_____________________指针常量___________________
int DaysInMonth=30;
int * const pDaysInMonth=&DaysInMonth;
cout<<"pDaysInMonth30="<<pDaysInMonth<<endl;
* pDaysInMonth=31;//可以
cout<<"pDaysInMonth31="<<pDaysInMonth<<endl;//地址是不变的
int DaysInLunarMonth=28;
//pDaysInMonth=&DaysInLunarMonth;//不可以改变指针地址
//_____________________双常量指针___________________
int HoursInDay=24;
const int * const pHoursInDay=&HoursInDay;
// * pHoursInDay=25;//不可以
int DaysInMonth=30;
// pHoursInDay=&DaysInMonth;//不可以