const关键字

来源:互联网 发布:js parentnode 编辑:程序博客网 时间:2024/06/10 04:22

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

1.将对象固化

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

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

//.hstruct A{const int m_i ;     //error,m_i is not static val};struct B{const static int m_i ;     //ok};//.cppconst A::i = 10;  //OKconst 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; //OKint &ref_m = const_i; //error,nonconst reference to a const object


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

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

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