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对象的指针,前者,不能给它重新赋值使之指向其他对象,而后者不能用于修改它指向的对象。

  • 相关阅读:
    JS和Flash相互调用
    xml的应用
    随机验证码
    模块 time
    第一天 注册成功
    我的第一篇博客
    git
    2018-02-27
    25
    建站之星
  • 原文地址:https://www.cnblogs.com/delphi2014/p/4022979.html
Copyright © 2011-2022 走看看