C++ —— const详解

本文首发在我的个人网站,欢迎来玩。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对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值