C++编程思想读书笔记--之const



C++ const

  • const在标准C中是用来定义常量的
    而C++设计当初是考虑使用const代替#define 宏进行值代替
    C++中主要有两个作用:1、值代替,2、指针
  • 值代替
    • 文本代替
      • #define 是在预处理的时候做文本代替,不占存储空间,也没有类型检查
        const 可以定义类型,占存储空间

        const int BUFSIZE = 100;
        char sz[BUFSIZE];
    • 用于集合
      • const可用于集合,但集合中的值不能在编译期间使用
        const int i[] = {1,2,3,4};
        char sz[i[1]]; //非法
  • 指针
    • 指向const的指针
      • const 修饰指针正指向对象  const int * X;

        const int * X;(X是一个指针,它指向一个const int)
        X指向的值不能变,但X的地址可以变
        • int d1 = 1;
          const  int *X = &d1;
          X = &d1; //合法
        • int d1 = 1;
          const int * X = &d1;
          *X = d1; //非法
    • const指针
      • const 修饰存储在指针本身的地址  int * const X;

        int d = 1;
        int * const X = &d;(X是一个指针,这个指针是指向int的const指针)
        编译器要求给它一个初始值,X的地址不能变,但指向的值可以变。

        • int d1 = 1;
          int *const X = &d1;
          *X = d1; //合法

        • int d1 = 1;
          int *const X = &d1;
          X = &d1; //非法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值