【持续更新】
1. Const 变量
在全局作用域里定义的非const变量,在整个程序中都可以访问,其默认为extern。
例如:
//file_1.cpp
int counter = 2 ;
//file_2.cpp
extern int counter;
++counter;
在全局作用域里定义的const变量,其作用域为该变量所属文件,此时const变量转换成了一个常量,且在定义后不能被修改,所以在定义时必须初始化。
例如:
//file_3.cpp
const int bufSize =0;//定义const变量,作用域为file_3.cpp
bufSize = 520;//错误,对const变量赋值将导致错误
需要将const变量作用域变为全程序,只需要做extern定义和申明即可。
例如:
//file_4.cpp
extern const int iSize =512;;//
//filce_5.cpp
extern const int iSize;
void fun()
{
std::cout<<iSize<<std::endl;
}
2. const引用
const引用是指向const对象的引用
例如:
const intival=1024;//定义const变量
const int &iref =ival;//OK 定义指向const变量的引用,即const引用
int &iref2 = ival;//error不能将非const引用指向const变量
可以将多种形式的值赋给const引用,例如不同类型的类型、右值、常量值、非const对象、const对象
例如:
doule d=1.0;
int i1=2;
const int i2 = 3;
const int &ref1 =1;//OK
const int &ref2 =i+2;//ok
const int &ref3 =d;//ok
const int &ref4 =i2;//ok
但是非const引用则只能使用非const对象赋值。
例如:
doule d=1.0;
int i1=2;
const int i2 = 3;
int &ref1 =1;//error
int &ref2 =i+2;//error
int &ref3 =d;//error
int &ref4 =i2;//error
int &ref5 =i1;//OK
3 const 指针
指向const型变量的指针定义:
const double *pd1; //pd1指向的对象内容不可变,即*pd1=3.13是错误的。
const指针变量定义:
double d = 3.13;
double * const pd2 = &d;//pd2本身是const的,对pd2 = pd2将错误,但*pd2 = 20是正确的。
指向const型变量的const指针定义:
const double d3 = 3.13;
const double * const pd3 = &d3;//pd3本身是const的,且pd3也指向const double。