const用法

1.const 修饰成员变量 
example1:
  int a1=3;   ///const封锁a1,不能被修改
  a1 = 3//报错,因为定义常量之后不能成重新赋值!!

example2:

const names = [];
names = [1,2,3] //出错,因为变量names指向的地址不能发生改变,应始终指向[]所在的地址!!!  [1,2,3]与[]不是同一个地址

//不会报错,因为names指向的地址不变,改变的只是内部数据
const names = [];
names[0] = 1
names[1] = 2
names[2] = 3

example3:

 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     int a1=3;   ///non-const data
 5     const int a2=a1;    ///const data
 6 
 7     int * a3 = &a1;   ///non-const data,non-const pointer
 8     const int * a4 = &a1;   ///const data,non-const pointer
 9     int * const a5 = &a1;   ///non-const data,const pointer
10     int const * const a6 = &a1;   ///const data,const pointer
11     const int * const a7 = &a1;   ///const data,const pointer
12 
13     return 0;
14 }

const修饰指针变量时:

  (1)只有一个const,如果const位于*左侧,表示指针所指数据是常量,不能通过解引用修改该数据;指针本身是变量,可以指向其他的内存单元。

  (2)只有一个const,如果const位于*右侧,表示指针本身是常量,不能指向其他内存地址;指针所指的数据可以通过解引用修改。

  (3)两个const,*左右各一个,表示指针和指针所指数据都不能修改。

2.const修饰函数参数

传递过来的参数在函数内不可以改变,与上面修饰变量时的性质一样。

void testModifyConst(const int _x) {
     _x=5;   ///编译出错
}

 

const int a[9] = {0x22, 8, 0x1C, 8, 0x21, 8, 0x2D, 12, 0x00};

void CustomVoice(const int *b)
{
  //传递数据,不改变变量的值
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值