一、const 关键字
1、定义常量
const int PI = 3.1415;
2、修饰函数
void Function(int a) const
{
}
该关键字限定成员函数不可修改成员变量
3、修饰变量
void Test1(int const* p)
{
*p = 12; //error C3892: “p”: 不能给常量赋值
p++; //ok
}
void Test2(int* const p)
{
*p = 12; //ok
p++; //error C3892: “p”: 不能给常量赋值
}
说明:const 在*的左侧,说明指针指向的内容不可修改,如test 1,如果const 在*右侧,说明指针变量不可修改(指针本身)
二、const 和mutable
volatile class B : public A1,public A2
{
public:
mutable int a1;
int a2;
};
void main()
{
const B b;
b.a1 = 12; //ok
b.a2 = 21; // error C3892: “b”: 不能给常量赋值
}