const與指標型別
定義一個指標*p:
const int* p = NULL; int const* p = NULL; int* const p = NULL;
上面兩行定義完全等價,第三行則不同,
下面兩行定義也完全等價:
const int* const p = NULL; int const* const p = NULL;
舉例說明:
int x = 3; const int* p = &x; //p=&y; 正確 //*p=4; 錯誤
const修飾的是*p,所以通過*p修改x的值是錯誤的,
int x = 3; int* const p = NULL; //p=&y; 錯誤
const修飾的是p,p只能指向一個地址,不能再改變,
const int x = 3; const int* const p = &x; //p=&y; *p=4; 都是錯誤的
上面這種情況,就不能再做任何修改,
const與參考型別
int x = 3; const int& y = x; //x=10; 正確 //y=20; 錯誤
y被const修飾,所以不能通過y去修改x的值,
更多示例:
const int x = 5; x = 5; //錯誤 int x = 3; const int y = x; y = 5; //錯誤 int x = 3; const int* y = &x; *y = 5; //錯誤
int x = 3, z = 4; int* const y = &x; y = &z; //錯誤 const int x = 3; const int& y = x; y = 5; //錯誤
const int x = 3; int* y = &x; //錯誤 int x = 3; const int* y = &x; //正確
上面這個示例,前者x是不可變的,而y是可變的,如果我們定義一個可變的指標指向一個不可變的變數,那么這就意味著存在風險,我們可以通過指標去修改x的值,這種情況編譯器是不允許存在的,所以錯誤;對于后者,指標只有讀權限,x則有讀和寫的權限,我們用一個權限小的物件接受一個權限大的物件這是允許的,而用一個權限大的物件接受一個權限小的物件則不允許,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/59722.html
標籤:C++
上一篇:演算法訓練 第五次作業:字串排序
