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=...是错的。
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值