zoukankan      html  css  js  c++  java
  • 关键字const用于指针!

    声明为const的变量,可确保变量的取值在整个生命周期内都固定为初始化值

    const指针有种:

    First:指针指向的数据为常量,不能修改,但可以修改指针包含的地址,既指针可以指向其他地方。

    1 int HoursInDay = 24;
    2 const int* pInteger = &HoursInDay;//cannot use pInteger to change HoursInday
    3 int MothsInYear = 12;
    4 pInteger = &MonthsInYear;//OK
    5 *pInteger = 13;//fail:cannot change data
    6 int* pAnotherPointerToInt = pInteger; //fails:cannot assign const to non-const
    Second:指针包含的地址是常量,不能修改,但可以修改指针指向的数据。
    1 int DaysInMoth = 30;2 int* const pDaysInMoth = &DayInMoth;
    3 *pDaysInMoth = 31;//OK
    4 int DaysInLunarMonth = 28;
    5 pDayInMoth = &DaysInLunarMonth;//fails:Cannot change address!
    Third:指针包含的地址以及它指向的值都是常量,不能修改。
    1 int HoursInDay = 24;
    2 const int* const pHoursInDay = &HoursInDay;
    3 *pHoursInDay = 25;//fails:cannot change pointed value
    4 int DaysInMonth = 30;
    5 pHoursInDay  = &DaysInMonth;//fails: cannot change pointer value
    讲指针传递给函数时,这些形式的const很有用。函数参数应声明为最严格的const指针,以确保函数不会修改该指针指向的值,让函数更容易维护。

    懒惰不会让你一下子跌到 但会在不知不觉中减少你的收获; 勤奋也不会让你一夜成功 但会在不知不觉中积累你的成果 越努力,越幸运。
  • 相关阅读:
    angular 路由动态加载JS文件
    使用AngularJS处理单选框和复选框的简单方法
    angularjs 请求后端接口请求了两次
    angular ui.router 路由传参数
    linux 安装svn服务器
    gulp css 压缩 合并
    ajax 实现跨域
    [codeforces 1366D] Two Divisors
    Namomo Test Round 1 题解
    Race(淀粉质)
  • 原文地址:https://www.cnblogs.com/Rainingday/p/5943811.html
Copyright © 2011-2022 走看看