const对象和const函数

  当一个类的函数的参数表不同时,能重载函数,  
  当函数的const性不同时,也能重载函数。  
  如下所示:  
   
  #include   "a.h"//定义了CA类  
  class   CBigClass  
  {  
  public:  
  CBigClass(CA   value):m_value(value)   {}  
  const   CA&   GetValue()   const{return   m_value;}  
  CA&   GetValue()   {return   m_value}  
  private:  
  CA   m_value;  
  }  
  //客户端代码如下:  
  CA   ca;  
  CBigClass   bc1(ca);  
  CA   &value1   =   bc1.GetValue();   //调用非const版本的GetValue  
  const   CBigClass   bc2(ca);  
  const   CA   &value2   =   bc2.GetValue();   //调用const版本的GetValue  
   
  都没有问题。(哇,不会这个你也看不懂吧,如果真的不懂,建议你看看其他相关的帖子)  
  但我们要接着问,为什么当const性不同时,也能重载函数呢?  
  是不是又是一个例外和后门?  
  答案是:   不是。  
  为什么呢?  
  提示一下,编译器会自动给每一个函数加一个什么参数呢?  
  对了,就是this指针。  
  在一个类的函数后面加上const后,就表明这个函数是不能改变类的成员变量的(加了mutable修饰的除外)。  
  实际上,也就是对这个附件上的this指针加上了const修饰。  
  这样一来,函数的参数表就不一样了,每一个CBigClass的对象都会调用正确版本的GetValue函数。  
   
  那么,如果缺少某个版本的GetValue时会怎么样呢?  
  有了前面的理论基础,结论就很明显了。  
   
  1.   如果缺少非const版本的GetValue函数,  
  代码如下:  
  #include   "a.h"//定义了CA类  
  class   CBigClass  
  {  
  public:  
  CBigClass(CA   value):m_value(value)   {}  
  const   CA&   GetValue()   const{return   m_value;}  
  private:  
  CA   m_value;  
  }  
  //客户端代码如下:  
  CA   ca;  
  const   CBigClass   bc2(ca);  
  const   CA   &value2   =   bc2.GetValue();   //OK!调用const版本的GetValue  
  CBigClass   bc1(ca);  
  const   CA   &value1   =   bc1.GetValue();   //??为什么也调用const版本的GetValue?  
   
  咦,为什么非const的对象bc2也会调用const版本的GetValue呢?  
  哦,这是因为在没有对应的const版本函数时,编译器会把非const对象的this指针转化为const的指针。  
  大家知道,这是没有问题的。如:  
  int   *p1   =   NULL   ;  
  const   int   *p2   =   p1;   //OK,没有问题  
   
  哈哈,是不是有点意思了,还有更有意思的在后面。  
   
  2.   如果缺少const版本的GetValue函数  
  代码如下:  
  #include   "a.h"//定义了CA类  
  class   CBigClass  
  {  
  public:  
  CBigClass(CA   value):m_value(value)   {}  
  CA&   GetValue()   {return   m_value;}  
  private:  
  CA   m_value;  
  }  
  //客户端代码如下:  
  CA   ca;  
  CBigClass   bc1(ca);  
  CA   &value1   =   bc1.GetValue();   //OK!调用非const版本的GetValue?  
  const   CBigClass   bc2(ca);  
  const   CA   &value2   =   bc2.GetValue();   //哈哈,编译错误,  
  //cannot   convert   'this'   pointer   from   'const   class   CBigClass'   to   'class   CBigClass   &'  
  看见了没有,其实就是这么回事。  
  再简单一点如下:  
  const   int   *p1   =   NULL   ;  
  int   *p2   =   p1;   //编译错误,同理:cannot   convert   from   'const   int   *'   to   'int   *'  
  也就是编译器会企图把const的bc2的this指针传给非const型的、附加上去的this参数,  
  当然会编译通不过了。  
  说白了,就是:   非const   型的指针能给const的指针  
  而const   型的指针不能给非const型的指针。  
  这个大家当然都知道,也能理解。  
  因为   加上一个const不会   有什么恶劣的后果,  
  而随便   去掉一个const性,也就不一样了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值