imooc 学习总结——离港篇:C++之const关键字
2017-03-12 12:13
281 查看
Const——控制数据的类型
1.const与基本数据类型int x = 10;//x是变量,之后x的值可以改变 const int x = 10;//x是一个常量,x的值不可变
2.const与指针类型
几种const修饰指针表量的形式
const int *p=NULL; int const *p=NULL; //两个表达式是完全等价的 int * const p=NULL; //这个则与前两个不同
const int * const p = NULL; int const * const p = NULL; //两个表达式完全等价
例1
int x =3; const int *p = &x; //p = &y;正确 // *p = 4;错误
变量 | 存储地址 | 存储内容 |
---|---|---|
x | &x | 3 |
p | &p | &x |
例2
int x =3; int const *p = &x; //p = &y;错误
变量 | 存储地址 | 存储内容 |
---|---|---|
x | &x | 3 |
p | &p | &x不可改变 |
例3
const int x =3; const int * const p = &x; //*p = 4; p = &y;都是错误的
变量 | 存储地址 | 存储内容 |
---|---|---|
x | &x | 3不可改变 |
p | &p | &x不可改变 |
3.const与引用
例1
int x =3; const int &y = x; // x = 10; 正确 //y = 20;错误
变量 | 存储地址 | 存储内容 |
---|---|---|
x | &x | 3 |
例2
const int x = 3; x = 5; false int x = 3; const int y = x; y = 5; false int x =3; const int *y = &x; *y = 5; false int x = 3,z = 4; int * const y = &x; y = =&z false const int x = 3; const int &y = x; y = 5; false // 对比 (1)const int x = 3; int *y = &x; false // x是一个常量,但用一个指针变量指向这个常量,则可能通过指针变量改变常量,计算机不允许,所以不通过。 (2)int x =3; const int *y = &x; true
const 能控制一个变量为常量,它与define不同的是,编译时系统并不会发现define的语法错误,所以更提倡用const定义常量。
相关文章推荐
- imooc 学习总结:C++之离港篇
- imooc 学习总结——离港篇:C++内存管理
- imooc 学习总结——离港篇:C++函数新特性
- C++中Const关键字总结
- C++学习小记之static和const关键字
- C/C++日常学习总结(第一篇)const用法及printf的执行顺序
- C++学习--const用法总结
- 标准C++中const关键字的用法总结
- C++学习笔记---const 关键字
- C++学习之const整理总结
- c++ const关键字 总结
- C++和C语言const区别关键字总结
- 【C++学习】const关键字释疑
- C++学习之路—const用法总结
- C/C++ const关键字用法总结
- C++ const 关键字的简单总结
- C++ const关键字 总结
- c++中const关键字全面总结
- C++学习笔记7,const关键字的使用(一)。
- C++中const关键字的使用总结