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 只能用来声明不能定义
第二点貌似没什么用。在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
常量指针与指针常量的区别与上面一样。