天天看点

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

}

继续阅读