天天看點

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=...是錯的。

}

繼續閱讀