const 修饰成员函数体
经过const修饰的变量表示不能被修改这个容易理解,例如
const int kInt = 0; // kInt 不能再被赋予其他值const int getValue(const char *key); // 返回值为不能被修改,函数体内不能修改参数的值
后来碰到一些写法如
const int getValue(const char *key) const;
对于最后一个const不甚理解,查资料后才明白这个用于类的成员函数修饰函数体,表示该函数体内类的成员变量的值不能被改变
class Test {public:void setValue(const int value) const {_value = value; // error C3490: '_value' cannot be modified because it is being accessed through a const object}private:int _value;};
而const修饰函数体也只能用于类的成员函数,如果用于普通函数
void test() const {int k = 0; // error C2270: 'test' : modifiers not allowed on nonmember functions}
const 是个好东西,有助于增强代码的健壮性,所以能用的地方都用上吧!

浙公网安备 33010602011771号