• c++:const修饰指针


    在开始之前:

    一般指针的定义:

    int* number = 6;         // *number是数字6。
    
    int ducks = 12;
    int* birddog = &ducks;  // 把birddog(而不是*birddog)的值设置为&ducks。

    *运算符被称为间接符号,或者解引用。
    用于指针时,可以得到该地址存储的值。

    而 int*是一种复合类型,是指向int的指针。

    第一种const的情况:

    int age = 39;
    const int* pt = &age;

    这里的const只能防止修改pt指向的值(这里是39), 而不能防止修改pt的值。


    也就是说,可以将一个新的地址赋给pt:

    int sage = 80;
    pt = &sage;

    但仍不能使用pt来修改它指向的值(现在为80)。

    int grop = 16;
    int chips = 12;
    const int* p_snack = &grop;
    
    *p_snack = 20;        // no, 禁止修改 p_snack指向的值
    p_snack = &chips;     // ok, p_snack可以指向另一个变量

    第二种const的情况:

    int sloth = 3;
    const int* ps = &sloth;        // a pointer to const int
    int* const finger = &sloth;    // a const pointer to int

    在最后一个声明中,关键字const的位置与以前不同。
    这种声明格式使得finger只能指向sloth,但允许使用finger来修改sloth的值。
    中间的声明不允许使用ps来修改sloth的值,但允许将ps指向另一个位置。
    简而言之,finger和*ps都是const, 但*finger和ps不是

    int grop = 16;
    int chips = 12;
    int* const p_snack = &grop;
    
    *p_snack = 20;        // ok, p_snack可以用来修改值
    p_snack = &chips;     // no, 禁止改变p_snack指向的变量

    最后

    把 int 去掉之后, 就知道const修饰是什么:

    int sloth = 3;
    const int* ps = &sloth; 变成 -> const *ps = &sloth; // const 修饰的是 *ps int* const finger = &sloth; 变成 -> * const finger = &sloth; // const 修饰的是 finger
  • 相关阅读:
    MVC4学习-View(0)
    javascript与常用正则表达式
    uhfreader&rfid标签测试
    WebClient文件上传很方便哈
    NAudio的简单用法
    与wmi交互,调非托管代码,单元测试遇到的一些问题
    我在这里骑美团单车被交警罚了50元,这个地方不能骑共享单车大家留意了
    发邮件,美化table格式
    学习jwt的简单使用
    学习redis的基本使用
  • 原文地址:https://www.cnblogs.com/weishuan/p/12269195.html
Copyright © 2020-2023  润新知