zoukankan      html  css  js  c++  java
  • 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数据;


  • 相关阅读:
    AutoMapper在ABP框架
    Github for Windows使用介绍
    Net中的反应式编程
    webstorm创建nodejs + express + jade 的web 项目
    Nancy 框架
    Quartz.NET 任务调度框架
    从电商秒杀与抢购谈Web系统大规模并发
    SVN中tag branch trunk用法详解
    Hsql中In没有1000的限制
    Gradle sourceCompatibility has no effect to subprojects(转)
  • 原文地址:https://www.cnblogs.com/holyson/p/3975036.html
Copyright © 2011-2022 走看看