const Pointers and Pointer to const Objects 常量指針和指向常量對象的指針

//英文來源:C++ Primer, 4th edition

    //Part of the problem in reading const declarations arises because the 'const' can go either before or after the type.
    //爲什麼有const的代碼閱讀起來會比較困難呢?因爲const可以出現在類型的前面或後面。

int main()
{
    char ch='a';
    char* const P1=&ch;//指針本身是常量。
    //As with any 'const', we must initialize a 'const' pointer when we create it.
    //正如任何常量一樣,常量指針必須初始化。


    //指針指向的內容是常量。以下2句是等價的。
    const char *P3;
    char const *P4;


    P3=&ch;
    *P3='b';//錯誤的!
    //Although 'ch' is not a 'const', any attempt to modify its value through P3 results in a compile-time error.
    //無論P3指向的內容是否常量,都不能通過P3修改其指向的內容。即*P3=...是錯的。
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章