C++的const可以非常灵活的摆放,例如:const int i、int const i、const int* p、int const *p、int* const p 等等,很多人会因此感到困惑,甚至于不使用const,我也是这样的。作为过来人,有必要说的是,其实const常用的也就这么几种(欢迎大家补遗):
1、修饰变量(variable)
const放在最前面修饰变量,例如:const int i、const int* p,这表明变量的内容不能改变,对i和*p不能进行赋值,例如 i = 20 或 *p = 20,编译器会报错。
const放在指针名称前,例如:int* const p,这表明指针的地址不能改变了,例如:++p是不允许的。
如果既想指针的内容无法改变,也想指针的指向的地址无法改变,则可以这么写:const int* const p,这也是一种常见的用法。
2、修饰函数(method)
const修饰函数常用在修饰返回值为指针的函数体上,例如:
int g = 0;
const int* GetValuePtr()
{
return &g;
}
const char* GetStr()
{
return "Hello";
}
这样就表明返回的指针指向的内容,调用者不要去改动。对于调用方,也只能声明用const修饰的指针去调用,例如:
const int* i = GetValuePtr();
const char* p = GetStr();
如1所示,这样声明指针,当然也就无法修改指针内容了。
3、修饰类成员函数(method of class)
const修饰非类的函数的果效同样作用于类成员函数上,特殊的是类的成员函数还可以在声明的末端用const修饰,例如:
class CMyClass
{
public:
CMyClass();
~CMyClass();
public:
int GetValue() const;