通过将变量声明为 const 的, 可确保变量的取值在整个生命周期内都固定为初始值。
这种变量的值不能修改,因此不能将其用作左值。
指针也是变量,因此也可将关键字 const 用于指针。然而,指针是特殊的变量,包含内存地址,还
可用于修改内存中的数据块。因此, const 指针有如下三种。
• 指针包含的地址是常量,不能修改,但可修改指针指向的数据:
int daysInMonth = 30;
int* const pDaysInMonth = &daysInMonth;
*pDaysInMonth = 31; // OK! Data pointed to can be changed
int daysInLunarMonth = 28;
pDaysInMonth = &daysInLunarMonth; // Not OK! Cannot change address!
• 指针指向的数据为常量,不能修改,但可以修改指针包含的地址,即指针可以指向其他地方:
int hoursInDay = 24;
const int* pointsToInt = &hoursInDay;
int monthsInYear = 12;
pointsToInt = &monthsInYear; // OK!
*pointsToInt = 13; // Not OK! Cannot change data being pointed to
int* newPointer = pointsToInt; // Not OK! Cannot assign const to non-const
• 指针包含的地址以及它指向的值都是常量,不能修改(这种组合最严格):
int hoursInDay = 24;
const int* const pHoursInDay = &hoursInDay;
*pHoursInDay = 25; // Not OK! Cannot change data being pointed to
int daysInMonth = 30;
pHoursInDay = &daysInMonth; // Not OK! Cannot change address
将指针传递给函数时,这些形式的 const 很有用。函数参数应声明为最严格的 const 指针,以确保
函数不会修改指针指向的值。这可禁止程序员修改指针及其指向的数据。
将关键字 const 用于指针
最新推荐文章于 2024-07-17 15:26:15 发布