首页 > 其他 > 详细

const 修饰成员函数体

时间:2016-08-11 15:41:54      阅读:238      评论:0      收藏:0      [点我收藏+]
经过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 是个好东西,有助于增强代码的健壮性,所以能用的地方都用上吧!





const 修饰成员函数体

原文:http://www.cnblogs.com/mforestlaw/p/5760922.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!