const與指針

聲明指針時,可以在類型前或後使用關鍵字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進行保護。

務必將指針設置爲空,而不要讓它未被初始化(懸浮) 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章