const成员函数、const类对象、mutable数据成员

1. const成员函数 只是告诉编译器,表明不修改类对象. 但是并不能阻止程序员可能做到的所有修改动作,比如对指针的修改,编译器可能无法检测到
2. 类体外定义的const成员函数,在定义和声明处都需要const修饰符
 1 class classname
 2 {
 3 public:
 4     classname() {}
 5     ~classname();
 6 
 7     void foo()  const;
 8     char &operator[](int i);
 9 private:
10     // dot.gif.
11 }
12 
13 void classname::foo()  const
14 {
15 // dot.gif
16 }
17 
18 char &classname::operator[](int i)
19 {
20 //..
21 }
22 int main()
23 {
24      const classname obj();
25     obj.foo();//ok
26     obj[2];//error,coz [] not const
27 }
28 

3. const对象为常量对象,它只能调用声明为const的成员函数。但是构造函数和析构函数是唯一不是const成员函数却可以被const对象调用的成员函数。 当然,一般对象当然也可以调用const成员了
 1  class  A
 2  {
 3  public :
 4      A( int  x,  int  y) : _x(x), _y(y) {}
 5       // int get() { return _x;}
 6       int   get ()  const  {  return  _y;}
 7  private :
 8       int  _x, _y;
 9  };
10 
11  int  main()
12  {
13      A obj( 2 3 );
14       const  A obj1( 2 3 );
15      cout  <<  obj. get ()  <<   "   "   <<  obj1. get ();//3 3
16      
17       return   0 ;
18  }
19 

 1  #include  < iostream >
 2  using   namespace  std;
 3 
 4  class  A
 5  {
 6  public :
 7      A( int  x,  int  y) : _x(x), _y(y) {}
 8       int   get () {  return  _x;}
 9       // int get() const { return _y;}
10  private :
11       int  _x, _y;
12  };
13 
14  int  main()
15  {
16      A obj( 2 3 );
17       const  A obj1( 2 3 );
18      cout  <<  obj. get ()  <<   "   "   <<  obj1. get ();
19       // 错误,obj1为常量对象,不能调用非const方法
20       return   0 ;
21  }

4. const成员函数可以被相同参数表的非const成员函数重载
 1  #include  < iostream >
 2  using   namespace  std;
 3 
 4  class  A
 5  {
 6  public :
 7      A( int  x,  int  y) : _x(x), _y(y) {}
 8       int   get () {  return  _x;}
 9       int   get ()  const  {  return  _y;}
10  private :
11       int  _x, _y;
12  };
13 
14  int  main()
15  {
16      A obj( 2 3 );
17       const  A obj1( 2 3 );
18      cout  <<  obj. get ()  <<   "   "   <<  obj1. get ();
19       //  2  3
20       return   0 ;
21  }
22 

4. 为了允许修改一个类的成员变量,即使是一个const对象的数据成员,于是引入了mutable
通过将数据成员声明为mutable, 表明此成员总是可以被更新,即使在一个const成员函数中。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值