定义常量
被const
修饰过的变量不能被修改,故此具有常量之称。如果类的成员变量是常量,那么在初始化的时候必须初始化。
const int MAX = 100;
MAX = 300; // 提示语法错误
修饰函数
const
可以修饰函数的返回值,参数及,函数的定义体,被const修饰会受到强制的保护,能防止意外的修改,从而提高函数的健壮性。
1.修饰参数
不能在定义体中修改形参的值
// 函数声明
void updateWithID(const int id);
// 函数定义
void updateWithID(const int id)
{
id = 0; // 提示语法错误!
}
2.修饰返回值
被修饰的返回值不能作为左值,只有作为右值使用
// 函数声明
const int getNum();
getNum() = 10; // 提示语法错误!
3.修饰函数定义体
被const
修饰的函数定义体的函数能被const
或者非const
对象调用,但是const
对象只能调用被const
修饰过定义体的函数。
// 函数声明
void getDescription() const;
// 函数定义
void getDescription() const
{
// code
}