const Pointers and Pointer to const Objects 常量指针和指向常量对象的指针

来源:互联网 发布:企业数据意识改进 编辑:程序博客网 时间:2024/05/20 04:27

//英文来源: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=...是错的。
}
0 0
原创粉丝点击