const 使用一二
2016-01-10 22:08
288 查看
Primer C++ 练习题4.20:
int i = -1;
const int ic = i;
对于这个,一开始认为,ic 作为const 类型变量,定义时应该给其赋常值,而此处给的是变量i,因此编译时会报错,但是经过验证,这个理解是错误的。
为此总结const的一些点:
1)const型变量在定义时必须初始化,但不一定非要用常量来初始化(如上);
2)const对象默认为文件的局部变量,通过指定const变量为extern,就可以在整个程序中访问const对象:
//file_1.cc
//define and initialize a const that is accessible to other files
extern const int bufSize = fcn();
//file_2.cc
extern const int bufSize; //uses bufSize defined in file_1
for(int index = 0; index != bufSize; ++index)
// ..
3)const引用可以绑定到不同但相关的类型的对象或绑定到右值,但非const引用只能绑定到同类型的对象。
const int &ri = 0; //绑定到右值
// 绑定到不同但相关类型
double i;
cosnt int &ref_i = i;
int i = -1;
const int ic = i;
对于这个,一开始认为,ic 作为const 类型变量,定义时应该给其赋常值,而此处给的是变量i,因此编译时会报错,但是经过验证,这个理解是错误的。
为此总结const的一些点:
1)const型变量在定义时必须初始化,但不一定非要用常量来初始化(如上);
2)const对象默认为文件的局部变量,通过指定const变量为extern,就可以在整个程序中访问const对象:
//file_1.cc
//define and initialize a const that is accessible to other files
extern const int bufSize = fcn();
//file_2.cc
extern const int bufSize; //uses bufSize defined in file_1
for(int index = 0; index != bufSize; ++index)
// ..
3)const引用可以绑定到不同但相关的类型的对象或绑定到右值,但非const引用只能绑定到同类型的对象。
const int &ri = 0; //绑定到右值
// 绑定到不同但相关类型
double i;
cosnt int &ref_i = i;
相关文章推荐
- css实现在div中垂直水平居中
- 最终个人作业
- poj-1125-Stockbroker Grapevine spfa模板
- javascript的特点
- rtmp发送H264及aac的音视频
- 使用adapter的notifyDataSetChanged时列表数据没有刷新
- 雷锋举报了快播
- 浅析多线程
- synchronized 用法总结
- Servlet3.0注解新特性笔记 (转载IBM)
- HPU:1879畅通工程(kruskal)
- document.body.scrollTop用法
- 触摸事件
- PPAPI插件与浏览器的交互过程
- 使用gdb调试Nginx worker进程
- UIScreen、UIWindow、UIView浅析
- 面试经历---YY欢聚时代(2015年11月21日上午初试、25日下午复试)
- Crazepony软件框架讲解
- 2016第一周日
- poj-2240- Arbitrage bellmanfoyd 模板