我從這個答案中知道一個指標const int** z應該被讀作
變數z是 [指向 [指向
const int物件的指標]的指標]。
在我看來,這意味著 if z=&ytheny應該是指向const int物件的指標。但是,以下代碼也可以編譯:
int x=0;
int const* y=&x;
const int** z=&y;
為什么一個int const*物件,即const指向 an的指標int而不是指向 a 的指標const int可以成為 的指向物件z?
uj5u.com熱心網友回復:
你誤解了 const 指的是什么。const 總是指的是它左邊的元素——除非它是最左邊的元素本身,它指的是右邊的元素。
這意味著它
int const *是一個指向 const int 的指標,而不是您認為的指向 int 的 const 指標。為了得到那個,你必須寫int * const
int const *并且const int *是完全相同的兩種書寫方式:指向 const int 的指標。
如果你從右到左閱讀宣告,你就明白了。如果 const 是最左邊的元素,閱讀時在它之前添加一個“that is”。前任:
const int *: 指向 int 的指標,即 const。int const *: 指向 const int 的指標。int * const: const 指向 int 的指標。const int * const: const 指向 int 的指標,即 const。int const * const: const 指向 const int 的指標。
注意1/2是一樣的,4/5是一樣的。1 和 4 被稱為“西常量”,因為常量在西/左側,而 2 和 5 被稱為“東常量”。
uj5u.com熱心網友回復:
為什么是
int const* 物件,即const指向int
不。
int const *并且const int *是同一型別。
人們有時更喜歡寫作,int const *因為它從右到左讀為"pointer to a const int",而const int *實際上讀為"pointer to an int (which is const)"。
const指向 an的指標intis int * const。
嘗試一下:
int a = 42;
const int * y = &a;
int const * z = &a;
*y = 24; // compile error assigning to const
*z = 24; // compile error assigning to const
int b = 0;
y = &b;
z = &b; // re-pointing non-const pointers is fine
*z = 1; // still a compile error
int * const x = &a;
*x = 24; // fine, assigning via pointer to non-const
x = &b; // error reassigning a const pointer
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/331748.html
下一篇:如何以相反的方式制作數字的平方?
