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 的前面,两种表达的方式也经常被讨论,但记住两者是等价的。

  • 相关阅读:
    Stacktraces java.lang.NoSuchMethodException: com.liuyang.action.UserAction.add()
    Error setting expression 'XXX‘'[Ljava.lang.with value '[Ljava.lang.String;@10101fb'
    Strut2的配置文件strust.xml报错:Package Action extends undefined package struts-default
    org.eclipse.ui.PartInitException: Unable to open editor, unknown editor ID: org.xmen.ui.text.XMLTextEditor
    如何让编译器实现struts2的xml提示
    Caused by: Unable to load configuration.
    OpenSUSE42.3 leap 开启ssh登陆
    LXDE桌面初始设置,Fedora27系统。
    OpenSUSE下支持托盘的邮件客户端Sylpheed
    Linux PuTTY 更改字体
  • 原文地址:https://www.cnblogs.com/guozqzzu/p/3595400.html
Copyright © 2011-2022 走看看