本文首发在我的个人网站,欢迎来玩。http://www.weekreport.cn/archives/541
1.使用const定义变量/常量
- c o n s t const const定义的变量只有类型为整数或枚举,且以常量表达式初始化时才能作为常量表达式。其他情况下它只是一个 c o n s t const const限定的变量,不要将与常量混淆。
如下面 b u f S i z e bufSize bufSize就是一个常量:
const int bufSize = 512;
-
任何修改 b u f S i z e bufSize bufSize的操作都会导致编译错误。
-
常量在定义后不能被修改,所以定义时必须初始化。
const std::string hi = "hello!"; //OK
const int i; // error,i未被初始化!
2.const对象默认为文件的局部变量
- 非 c o n s t const const变量默认为 e x t e r n extern extern,但全局作用域定义的 c o n s t const const变量是该变量所在文件的局部变量,要使 c o n s t const const变量能够在其他文件中访问,必须显式地指定它为 e x t e r n extern extern。
//非const对象
//file_1.cpp,定义
int counter = 0;
//file_2.cpp,声明
extern int countrt;
//const对象
//file_1.cpp,定义
extern const int counter = 0;
//file_2.cpp,声明
extern const int countrt;
- 设置默认情况的原因在于允许 c o n s t const const变量定义在头文件中。
3.const引用
-
c o n s t const const引用是指向 c o n s t const const对象的引用。
-
被 c o n s t const const限定的引用表示只读。
-
c o n s t const const引用可以初始化为 c o n s t const const对象或非 c o n s t const const对象。
非 c o n s t const const引用只能初始化非 c o n s t const const对象。
const int ival = 1024;
const int &refVal = ival; //ok
int &ref2 = ival; //error
-
c o n s t const const引用可以初始化为不同但相关的类型的对象或者是右值,如字面值常量;非 c o n s t const const引用只能初始化为与该引用同类型的对象。
原因在于用不同类型的对象初始化引用会发生类型转换,产生中间变量,期望通过引用改变源对象值是不现实的,引用只会改变中间变量的值。
基于上述原因,规定只有 c o n s t const const引用才能初始化为不同类型的对象,因为 c o n s t const const引用是只读的,没有修改值的需求,也就完全避免了上述问题。
double dval = 3.14;
const int &ri = dival;
编译器会将代码转换为如下形式:
int temp = 3; //产生一个int类型的中间变量
const int &ri = temp; //使用中间变量temp初始化ri
4.const对象可以定义在头文件中
-
头文件用于声明而非定义,但有三种例外:类、值在编译时就已知的 c o n s t const const对象