///const 指针的三种状态/
注意:const 的前后顺序
const 在类型之前 ---可以修改指针包含的地址,不能修改指针指向的值 const 在变量之前类型之后 ---可以修改指针的指向值,不能修改指针地址
// 1.指针指向的数据为常量,不能修改,但是可以修改指针包含的地址
/*
int HoursInDay = 24;const int* pInteger = &HoursInDay;cout<<HoursInDay<<" "<<*pInteger<<endl;
//*pInteger = 55; //不能通过指针修改指向的值
cout<<HoursInDay<<" "<<*pInteger<<endl;
int MonthsInYear = 12;
pInteger = &MonthsInYear; //可以修改指针指向的地址//*pInteger = 13;
//int *pAnotherPointerToInt = pInteger; //指针的类型不同不能用于拷贝
*/
//2.指针包含的地址是常量,不能修改,但可以修改指针指向的数据/*
int DaysInMonth = 30;int* const pDaysInMonth = &DaysInMonth;*pDaysInMonth = 31; //Ok! value can be change
int DaysInLunarMonth = 28;
//pDaysInMonth = &DaysInLunarMonth; Cannot change address!*/ //3.指针包含的地址以及它指向值都是常量,不能修改(这种组合最为严格)/*
int HoursInDay = 24;const int* const pHoursInDay = &HoursInDay;
//*pHoursInDay = 25; cannot change pointed value 不能修改指向的值
int DayInMonth = 30;
//pHoursInDay = &DayInMonth; cannot change pointer value 不能修改指针
*/
将指针传递给函数时,这些形式的const很有用。函数参数应声明为最严格的const指针,以确保函数不会修改指针指向的值。这让函数更容易维护,在时过境迁和人员更换尤其如此。
void CalcArea(const double* const pPi, //const pointer to const data
const double* const pRadius, //i.e.. nothing can be changed double* const pArea //change pointed value,not address ){ //check pointers before using! if (pPi && pRadius &&pArea) { *pArea = (*pPi) * (*pRadius) *(*pRadius); }} int main(){ const double PI = 3.14;cout << "Enter radius of circle: ";
double Radius = 0; cin >> Radius;double Area = 0;
CalcArea(&PI,&Radius,&Area);cout << "Area is = "<<Area<<endl;
}