聲明指針時,可以在類型前或后使用關鍵字const,也可在兩個位置都使用。例如,下面都是合法的聲明,但是含義大不同:
const int * pOne; //指向整形常量 的指針,它指向的值不能修改
int * const pTwo; //指向整形的常量指針 ,它不能在指向別的變量,但指向(變量)的值可以修改。
const int *const pThree; //指向整形常量 的常量指針 。它既不能再指向別的常量,指向的值也不能修改。
理解這些聲明的技巧在於,查看關鍵字const右邊來確定什么被聲明為常量 ,如果該關鍵字的右邊是類型,則值是常量;如果關鍵字的右邊是指針變量,則指針本身是常量。下面的代碼有助於說明這一點:
const int *p1; //the int pointed to is constant
int * const p2; // p2 is constant, it can't point to anything else
const指針和const成員函數
可以將關鍵字用於成員函數。例如:
class Rectangle
{
pubilc:
.....
void SetLength(int length){itslength = length;}
int GetLength() const {return itslength;} //成員函數聲明為常量
.....
private:
int itslength;
int itswidth;
};
當成員函數被聲明為const時,如果試圖修改對象的數據,編譯器將視為錯誤。
如果聲明了一個指向const對象的指針,則通過該指針只能調用const方法(成員函數)。
示例聲明三個不同的Rectangle對象:
Rectangle* pRect = new Rectangle;
const Rectangle * pConstRect = new Rectangle; //指向const對象
Rectangle* const pConstPtr = new Rectangle;
pConstRect是指向const對象的指針,它只能使用聲明為const的成員函數,如GetLength()。
const this 指針
將對象說明為const時,相當於該對象的this指針聲明為一個指向const對象的指針。const this指針只能用來調用const成員函數。
如果對象不應被修改,則按引用傳遞它時應使用const進行保護。
務必將指針設置為空,而不要讓它未被初始化(懸浮)