c++ const和指针代码说明

#include <iostream>

using namespace std;

int main()
{
    // 可以将const指针赋给const指针,但b不能把const指针赋给常规指针
    const float g_earth = 9.80;
    const float *pe = &g_earth;
    // float *pm = &g_earth; 错误

    // 一级间接关系
    int zz = 30;
    int *pd = &zz;  // *pd = 41 正确
    const int *pt1 = pd; //*pt1 = 41 错误 

    // 两级间接关系
    const int **pp2;
    int *p1;
    const int n=13;
    // pp2 = &p1       //不允许,但支持这么做
    // *pp2 = &n;      // 会让p1指向n
    // *p1 = 10;       // 有效,但改变了const n
    // cout<<*pp2<<*p1<<n;


    int age = 39;
    const int *pt = &age;   // pt指向const int,*pt的值不能修改,但pt本身的值可以修改
    age = 20;               // 因为age不是const,因此可以修改age的值,此时*pt的值也会改变
    int sage = 80;
    pt = &sage;             // pt指向sage,*pt的值为80
    cout<<"*pt:"<<*pt<<" "<<"age:"<<age<<endl;

    int sloth = 3;
    // 指针常量, 指向const int, 不能通过ps来修改sloth的值,但允许将ps指向令一个位置
    const int *ps = &sloth;     
    ps = &age;
    //常量指针,指向int, 无法修改指针本身的值,只能指向sloth,但可以使用*finger修改sloth的值
    int *const finger = &sloth; 
    *finger = 5;
    cout<<"sloth:"<<sloth<<endl;
    // const对象的const指针,stick只能指向sloth且*stick的值不能修改
    const int *const stick = &sloth; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值