const关键字

const关键字在C++中有两个作用:

1.将对象固化

const int const_i = 10; //OK
int val = 10;
const int const_a = val; //OK

const修饰类成员时该成员必须是静态变量。

//.h
struct A
{
const int m_i ;     //error,m_i is not static val
};

struct B
{
const static int m_i ;     //ok
};

//.cpp
const A::i = 10;  //OK
const static A::i = 10; //error,static 只能用来声明不能定义


2.const 对象默认为文件的局部变量

第二点貌似没什么用。在vc6.0环境中,test.h中定义const int i = 10; 在dlg.cpp中#include "test.h"后仍可使用i变量。


注意:

常量引用是指向const对象的引用。

const int const_i = 10;
const int &ref_i = const_i; //OK
int &ref_m = const_i; //error,nonconst reference to a const object


引用常量是指向某对象的常量引用。

int val =  10;
const int &cref_val = val; //OK
const int i = 10;
const int &cref_i = i; //OK

常量指针与指针常量的区别与上面一样。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值