(1)例:1. int i=1;
const int *cptr=&i;
*cptr=2; //出錯,cptr指向的是常量1
cout<<*cptr《注意: 指向 const 的指標常用作函式的形參。將形參定義為指向 const 的指標,確保傳遞給函式的實際物件在函式中不因形參而被修改。
(2)const pointer本身值不可改,但其指向的是否可改是根據指向的物件是否為const。
int i=10,tt=88; //若為const int i=10;也出錯
int *const cptr=&i;
*cptr=9; //可以
cptr=&tt; //出錯
cout<<*cptr<(3)const pointer to a const object 指標本身與其指向的物件均不可以改.
const int i=10;
const int *const cptr=&i;
總結:有加const的話,都是從右往左看的,即左邊修飾右邊的。
例:const int *cptr cptr是個int型指標, 這個int是常量
int *const cptr cptr(即指標)是const型,這個const是指向int的
const int *const cptr=&i; cptr是const型, 而第2個const是指向int的,而這個int是常量
原變數:int型 --> 指標變數 int *const p , const int *, const int *const pi=&a;
const int型 --> 指標變數const int *p, const int *const pi=&a;
附加:1 const string str;
string const str; //兩者一樣
2 string s;
typedef string *pstring;
const pstring cstr1 = &s; //1種
pstring const cstr2 = &s; // 2種all three decreations are the same type
string *const cstr3 = &s; // they're all const pointers to string
(書寫時一般把const放於前面,但宣告時建議const置於後面,便於理解)
筆記 C const與指標
const int p1 intconst p2 int const p3 在最後一種情況下,指標是唯讀的,也就是 p3 本身的值不能被修改 在前面兩種情況下,指標所指向的資料是唯讀的,也就是 p1 p2 本身的值可以修改 指向不同的資料 但它們指向的資料不能被修改。資料上 初學const,感覺資料...
c const指標與函式呼叫
在我的部落格中,已經討論了動態繫結和靜態繫結,以及在預設引數情況下虛函式的繫結情況。一般情況下,我們 是用非const的基類指標指向派生類物件,如果通過該指標呼叫虛函式則發生的動態繫結,如果我們定義乙個const指標,指向派生類的物件,如果派生類裡定義了同名的虛函式和 const函式,會發生什麼呼叫...
C const物件(常物件)
在 c 中,const 也可以用來修飾物件,稱為常物件。一旦將物件定義為常物件之後,就只能呼叫類的 const 成員 包括 const 成員變數和 const 成員函式 了。定義常物件的語法和定義常量的語法類似 const class object params class const object...