const 修饰成员函数体

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





posted @ 2016-08-11 14:49  琼'  阅读(437)  评论(0编辑  收藏  举报