zoukankan      html  css  js  c++  java
  • const 指针的三种使用方式

    ///////////////////////const 指针的三种状态/////////////////////

    注意:const 的前后顺序
    const 在类型之前 ---可以修改指针包含的地址,不能修改指针指向的值
    const 在变量之前类型之后 ---可以修改指针的指向值,不能修改指针地址

    // 1.指针指向的数据为常量,不能修改,但是可以修改指针包含的地址

    /*
    int HoursInDay = 24;
    const int* pInteger = &HoursInDay;

    cout<<HoursInDay<<" "<<*pInteger<<endl;

    //*pInteger = 55; //不能通过指针修改指向的值

    cout<<HoursInDay<<" "<<*pInteger<<endl;

    int MonthsInYear = 12;
    pInteger = &MonthsInYear; //可以修改指针指向的地址

    //*pInteger = 13;

    //int *pAnotherPointerToInt = pInteger; //指针的类型不同不能用于拷贝

    */


    //2.指针包含的地址是常量,不能修改,但可以修改指针指向的数据

    /*
    int DaysInMonth = 30;
    int* const pDaysInMonth = &DaysInMonth;

    *pDaysInMonth = 31; //Ok! value can be change

    int DaysInLunarMonth = 28;
    //pDaysInMonth = &DaysInLunarMonth; Cannot change address!
    */


    //3.指针包含的地址以及它指向值都是常量,不能修改(这种组合最为严格)

    /*
    int HoursInDay = 24;

    const int* const pHoursInDay = &HoursInDay;

    //*pHoursInDay = 25; cannot change pointed value 不能修改指向的值

    int DayInMonth = 30;

    //pHoursInDay = &DayInMonth; cannot change pointer value 不能修改指针
    */

    将指针传递给函数时,这些形式的const很有用。函数参数应声明为最严格的const指针,以确保函数不会修改指针指向的值。这让函数更容易维护,在时过境迁和人员更换尤其如此。

    void CalcArea(const double* const pPi,        //const pointer to const data
                        const double* const pRadius, //i.e.. nothing can be changed
                        double* const pArea              //change pointed value,not address
                       )
    {
           //check pointers before using!
           if (pPi && pRadius &&pArea)
          {
              *pArea = (*pPi) * (*pRadius) *(*pRadius);
          }
    }


    int main()
    {
    const double PI = 3.14;

    cout << "Enter radius of circle: ";
    double Radius = 0;
    cin >> Radius;

    double Area = 0;
    CalcArea(&PI,&Radius,&Area);

    cout << "Area is = "<<Area<<endl;
    }

  • 相关阅读:
    51单片机寄存器组的设置(转)
    51单片机堆栈深入剖析(转)
    do{...}while(0)的妙用(转)
    优化C/C++代码的小技巧(转)
    Struts2返回json
    详略。。设计模式1——单例。。。。studying
    [深入理解Android卷一全文-第十章]深入理解MediaScanner
    《python源代码剖析》笔记 Python虚拟机框架
    jQuery Validation让验证变得如此easy(三)
    mysql高可用架构方案之中的一个(keepalived+主主双活)
  • 原文地址:https://www.cnblogs.com/cci8go/p/3798986.html
Copyright © 2011-2022 走看看