• C++ const


    1、指针和const

    const常量指向一个非const变量

    int age=39;
    const int *pt=&age;

    该声明指出,pt指向一个const int,因此不能使用pt来修改这个值。换句话说*pt的值为const,不能被修改。

    *pt+=1;    //  invalid,因为*pt为const只读的.
    cin>>*pt;  // invalid,因为*pt为const只读的.

    常量pt的生命并不意味着,它指向的值实际上就是一个常量。因此可以通过修改age来改变pt的值

    *pt=20;    // invalid,因为*pt为const只读    
    age=20;    // valid,因为age没有被声明为const只读

    非const变量不能指向一个const常量

    int age=39;
    const int *pt=&age;       //valid
    
    const float g_earth=9.80;
    const float * pe= &g_earth;    //valid
    
    const float g_moon=1.63;
    float * pm=&g_moon;            //invalid

    在函数中将const数组赋值给非const数组

    const int months[12]={31,28,31,30,31,30,31,31,30,31,30,31}
    int sum(int arr[],int n);
    int j=sum(months,12); // not allowed

    上述函数调用试图将const指针(months)赋值给非const指针(arr),编译器将禁止这种函数调用。


    *尽可能使用const

    将指针参数声明为指向常量数据的指针有俩个理由:

    ①  这样可以避免由于无意间修改数据而导致的编程错误;

    ②  使用const使得函数能够处理const和非const实参,否则将只能接受非const数据;


  • 相关阅读:
    jQuery中常用方法和jQuery思维导图
    jQuery
    JS-AJAX and jQuery-AJAX
    Linux系统里导入maven项目
    maven项目里的ssh框架整合
    spring框架的两大核心:IOC和AOP
    JAVA的抽象类和接口
    JAVA面向对象的三大特征
    JAVA---面向对象
    JAVA---方法
  • 原文地址:https://www.cnblogs.com/holyson/p/3975036.html
Copyright © 2020-2023  润新知