const 关键词

来源:互联网 发布:中文通用域名 诈骗 编辑:程序博客网 时间:2024/06/01 09:23
常量标识 
     const int i=0; // 与 int const 等效
常量引用 
     const int &i=43;//与 int const等效
常量指针 
     int a=0;
     const int *i=&a;//i所指向值为常量 //与 int const等效
指针常量
     int a=0;     
     int *const i=&a;//i所指向的地址为常量 
     const int *const j=&a;//j指向的地址为常量,且其指向的值也为常量

非指针相关的const常量是一定要在定义的同时进行初始化。
     


常量引用与常量指针的共同注意点
     int a=10;
     const int &b=a;
     const int *c=&a;
     a=0;//此时b==0,*c==0。即常量指向变量,对变量的修改依旧影响到了常量的值。 

只在常量模式下可以进行的引用初始化
     int i=44;
     const int &r=42;
     const int &r2=r+i;
     //跨类型引用赋值
     double i=99;
     const  int &r=i;
     原因:防止若引用r不为const,r的变化就不会引起原值的变化。
     上述赋值转化为:
      int temp =i;
     const int &r=temp;
 
引入typedef关键字之后带来的疑惑
     typedef char *pstring;
     const pstring cstr = 0; // cstr is a constant pointer to char
     const pstring *ps; // ps is a pointer to a constant pointer to char 
     此时const pstring cstr = 0;不能翻译成const char *cstr = 0;,要将pstring看成一个类型,因此原cstr是一个常量指针,即指针的指向不能变。
 
     
0 0
原创粉丝点击