zoukankan      html  css  js  c++  java
  • C++ 之 指针详解篇(三)

      Const指针

    申明Const指针格式如下

       const int* p;

       int* const p1;

       const int* const p2;

    这些含义都各不相同,所以我们必须要会使用

      p是指向整形的常量的指针,它指向的值是不可更改的。

      p1是一个指向整形的常量指针。它指向的值可以修改,但p1不能指向其他变量

      p2是一个指向整形常量的常量指针。它指向的值不能修改,且这个指针也不能指向其他变量。

    示例

    class A    //申明类A
    {
      public:
        A();
        ~A();
        void setlength(int length){ilength = length;}
        int getlength()const{return ilength;}   
        void setWidth(int width){iwidth = width;}   
        int getwidth()const{return iwidth;} 
      private:
        int ilength;
        int iwidth;
    };
    A::A()
    {
       iwidth = 5;
       ilength = 10;
    }
    A::~A()
    {
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        A* ps = new A;  //声明了类A的指针并且动态的分配内存
        const A* pconstA = new A;  //声明了一个指向常量A的指针pconstA
        A* const pconstB = new A;  //声明了一个指向A的常指针pconstB
        cout<<"pS  "<<ps->getwidth()<<endl;      
        cout<<"pconstA: "<<pconstA->getwidth()<<endl;
        cout<<"pconstB: "<<pconstB->getwidth()<<endl;  //分别输出以上的值
        ps->setWidth(10);   //设置ps的宽度
        pconstB->setWidth(10);  //设置pconstB的宽度为10
        cout<<"ps "<<ps->getwidth()<<endl;
        cout<<"pconstA Width:"<<pconstA->getwidth()<<endl;
        cout<<"pconstB "<<pconstB->getwidth()<<endl;
        return 0;
    }

    输出结果为

      结合以上实例,我们可以得出结论。声明const指针和指向const对象的指针,前者,不能给它重新赋值使之指向其他对象,而后者不能用于修改它指向的对象。

  • 相关阅读:
    Android 9.png图片制作
    Android 基于Socket的聊天室
    poj 1659 Frogs' Neighborhood
    zoj 2836 Number Puzzle
    zoj 1372 Networking
    hdoj 4259 Double Dealing
    Direct2D (33) : 通过 ID2D1BitmapRenderTarget 绘制背景网格
    Direct2D (36) : RenderTarget.DrawText() 与 IDWriteTextFormat
    Direct2D (35) : 通过 DirectWrite 获取字体列表
    Direct2D (37) : 使用不同画刷绘制文本
  • 原文地址:https://www.cnblogs.com/delphi2014/p/4022979.html
Copyright © 2011-2022 走看看