c 常量指標與指向常量的指標

2021-05-25 02:43:09 字數 855 閱讀 6223

這是兩個初學者容易混淆的概念。比如,

t *pt = new t;

const t *pct  = pt;//指向常量(const t)的指標

t * const cpt = pt;//常量指標,指向t

不過使用乙個引用比使用乙個常量指標更簡單:

const t &rct = *pt; //不用const t* const

t &rt = *pt; //不用t* const

使用過程中,要注意三點:

1. 乙個指向常量的指標可以指向乙個非常量物件

2. 指向非常量的指標不可以指向常量物件 (行為未定義)

3. 乙個常見的誤解是,適用於指標的轉換同樣適用於指向指標的指標。事實上並非如此。

例如,我們知道乙個指向派生類的指標可被轉換為乙個指向其公共基類的指標:

=new

circle;

=c; 

//正確

因為circle 是乙個( is-a ) shape ,因而乙個指向 circle 的指標也是乙個 shape 指標。

然而,乙個指向 circle 指標的指標並不是乙個指向 shape 指標的指標:

**cc =&

c;**s 

=cc; 

//錯誤!

這裡兩種可以這樣理解:

typedef circle 

* lpcircle;

typedef shape 

* lp

shape;

lpcircle * cc = & c; lp

shape * s = cc;//錯誤,

lpshape和

lpcircle沒有 is-a的關係

常量指標與指向常量的指標

在日常交流中,當乙個 c 程式設計師說 常量指標 const pointer 時,其實他表達的意思往往是 指向常量的指標 pointer to const 真不幸,這是兩個完全不同的概念。t pt new t 乙個指向t的指標 const t pct pt 乙個指向const t的指標 t cons...

常量指標與指向常量的指標

以下所有 測試的ide為code blocks16.01 常量指標是指指標變數本身不可以改變的指標,但是可以通過指標變數修改所指向的變數,常量指標不能指向常量 int number1 10 int number2 20 const int number 30 int const pnumber1 n...

常量指標與指向常量的指標

1 include2 void main 編譯結果 hello.c in function main hello.c 8 2 error assignment of read only location p1 p1 2 企圖改變a的值 非法 hello.c 9 2 error assignment ...