const数据成员和const成员函数
const数据成员: 在对象创建后, 不可修改的数据成员.
const数据成员的初始化方式:
1.使用类内值(C++11支持)
2.使用构造函数的初始化列表
(如果同时使用这两种方式,以初始化列表中的值为最终初始化结果)
注意: 不能在构造函数或其他成员函数内,对const成员赋值!
- 类内初始值初始化const数据成员
//Human.h
class Human{
private:
const string bloodType = 'A'; //C++11支持的类内初始值
}
- 初始化列表初始化const数据成员
//Human.cpp
Human::Human(string bldType):bloodType(bldType){ //初始化列表
}
const成员函数: const成员函数内部, 不能修改任何数据成员.
const对象只能调用const成员函数.
class Human{
public:
void description() const; //const成员函数
}
void Human::description() const{
......
}