码迷,mamicode.com
首页 > 其他好文 > 详细

const 使用一二

时间:2016-01-10 22:41:24      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

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;

 

const 使用一二

标签:

原文地址:http://www.cnblogs.com/ruanbashezhe/p/5119687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!