• C++中的指针与const


    刚开始接触C++时,指针和const之间的关系有点混乱,现在总结如下:

    一、指向const变量的指针

    #include<iostream.h>
    void main()
    {
        const int *p=NULL;
        const int a=10;
        p=&a;
        cout<<"*p="<<*p<<endl;
        int b=100;
        p=&b;
        cout<<"*p="<<*p<<endl;
        //*p=200;    错误,不能通过修改指针来修改指针指向的内容
        b=200;
        cout<<"*p="<<*p<<endl;
    }

    不能通过修改指针来修改指针指向的内容,但可以修改指针的指向。

    另一种形式:

    int const *p=NULL;

    二、const指针

    #include<iostream.h>
    void main()
    {
        int a=10;
        int b=100;
        int * const p=&a;
        cout<<"*p="<<*p<<endl;
        //p=&b;        错误,不能通过修改const指针的指向来修改指针指向的内容 
        *p=200;
        cout<<"*p="<<*p<<endl;
    }

    不能修改指针的指向,但可以通过修改指针来修改指针指向的内容。

    不过这样也会报错:

    #include<iostream.h>
    void main()
    {
        const int a=10;
        int b=100;
        int * const p=&a;
        cout<<"*p="<<*p<<endl;
        //p=&b;        错误,不能通过修改const指针的指向来修改指针指向的内容 
        *p=200;
        cout<<"*p="<<*p<<endl;
    }

    报错如下:

    --------------------Configuration: 01 - Win32 Debug--------------------
    Compiling...
    01.cpp
    E:Program Files (x86)201411021.cpp(6) : error C2440: 'initializing' : cannot convert from 'const int *' to 'int *const '
            Conversion loses qualifiers
    Error executing cl.exe.

    01.exe - 1 error(s), 0 warning(s)

    而指向const变量的指针中不会有这样的问题。

    三、指向const变量的const指针

    #include<iostream.h>
    void main()
    {
        int a=10;
        int b=100;
        const int * const p=&a;
        cout<<"*p="<<*p<<endl;
        //p=&b;    错误,不能通过修改const指针的指向来修改指针指向的内容
        //*p=200;    错误,不能通过修改指针来修改指针指向的内容
    }

    不能通过修改指针来修改指针指向的内容,也不可以修改指针的指向。

    估计以后我都没有耐心看,也许那时这都不是事。


    欢迎访问我的的博客:www.wshunli.com

    -------------------

    已迁移文章:

    VMware 12安装Mac OS X 10.10

    http://www.wshunli.com/posts/65583447.html 

    Tomcat安装配置

    http://www.wshunli.com/posts/c8d48a24.html 

  • 相关阅读:
    VS2005使用AjaxPro.2
    一步步教你实现富文本编辑器(第三部分)
    Ajax实现在textbox中输入内容,动态从数据库中模糊查询显示到下拉框中
    一步步教你实现跨游览器的JS日历
    2009年中国10大网络公司业绩比较
    Beautiful smile and love
    NGINX 配置404错误页面转向
    wget使用范例
    mcrypt以及mhash扩展的安装!
    linux下常用压缩格式的压缩与解压方法
  • 原文地址:https://www.cnblogs.com/wangshunli/p/4077384.html
Copyright © 2020-2023  润新知