zoukankan      html  css  js  c++  java
  • 指针知识(五):指针(pointer)和常量(const)

    1.  我们知道,指针可以根据它包含的地址访问到变量值,而且也可以改变它所指的变量的值。

    但是,我们也可以声明这样的指针:能访问到它所指的值,但不能改变所指的这个值

    为了达到这样的目的,我们可以这样做:声明指针所指的类型为 const。例如:

         int x ;

       int y = 10;

         const int* p = &y;

         x = *p;      //ok:reading p

        *p = x;      //出错,*p 是常量,不能被改变

    这里,最初表达式 &y 是 int* 类型,但被赋值给类型为 const int* 类型的指针。我们要注意:指向非常量的指针可以被隐式转换成指向常量的指针

    但是反过来却不行。

    一个使用这种指向常量元素的指针例子是,它作为函数的参数:这时,函数就不能改变这种指针传过来的变量值了。

    #include <iostream>

    using namespace std;

    void increment_all (int* start, int* stop)

    {

      int * current = start;

      while (current != stop)

    {

      ++(*current); //指针指向的值增加

      ++current; //指针本身增加

    }

    }

    void print_all (const int* start, const int* stop)

    {

      const int * current = start;

      while (current != stop) {

      cout << *current << ' ';

      ++current; //指针本身增加

    }

    }

    int main ()

    {

      int numbers[] = {10,20,30};

      increment_all (numbers,numbers+3);

      print_all (numbers,numbers+3);

      return 0;

    }

    输出:   11

        21

        31

    函数 print_all 使用了指向常量元素的指针,print_all 中指针所指向的常量是不能被改变的,但 print_all 中的指针本身并不是常量,所以指针的值可以改变。

    2.  指针本身也可以是常量,声明方法是在符号 * 后加 const,下面几个语句:

    int x ;

    int* p1 = &x;

    const int* p2 = &x;      //指向常量的指针

    int* const p3 = &x;      //常量指针指向非常量值

    const int* const p4 = &x;    //常量的指针指向常量值

    在应用中,const 和 指针(printer)的混合使用不容易被掌握,但只要多加练习,积累经验,也可熟练的使用最合适的类型进行使用。

    3.  

    const int* p2 = &x;

    int const* p2 = &x;

    这两个语句是等价的,都是指向常量的指针。const 放在 int 的前面 或者 int 放在 const 的前面,两种表达的方式也经常被讨论,但记住两者是等价的。

  • 相关阅读:
    P1996 约瑟夫问题
    GIS Experience (十):OSM数据获取
    GIS Experience (九):高德室内地图建筑信息提取
    GIS Experience (十):Python地理空间数据分析
    GIS Experience (八):ArcGIS Desktop GP服务发布及调用
    GIS Experience (七):QGIS安装及使用教程
    GIS Experience (六):ArcGIS实践操作问题集
    GIS Experience (五):GeoServer安装及使用教程
    Spark集群框架搭建【VM15+CentOS7+Hadoop+Scala+Spark+Zookeeper+HBase+Hive】
    GIS Experience (四):ArcGIS Enterprise 10.6 (Windows)安装及部署图解
  • 原文地址:https://www.cnblogs.com/guozqzzu/p/3595400.html
Copyright © 2011-2022 走看看