函数重载之const

        我们知道,如果函数名相同,在相同的作用域内,其参数类型、参数个数,参数顺序不同等能构成函数重载。有趣的是如果同时在类中,对于函数名相同的const函数和非const函数能够构成重载,同时它们被调用的时机为:如果定义的对象是常对象,则调用的是const成员函数,如果定义的对象是非常对象,则调用重载的非const成员函数。例如:
#include <iostream>
using namespace std;
class A
{
public:
       A( int x )
       {
              m = x;
       }
      
       int func( void )
       {
            cout << "non-const" << endl;
            m = 1700; //本函数体没有声明为const,允许修改成员数据
            return m;
       }
      
       //函数体限制为const
       int func( void )const
       {
             cout << "const" << endl;            
             return m;
       }
private:
        int m;
};

int main( void )
{
    A b( 2002 );
    b.func( ); //调用 非const版本的func()
   
    const A c( 2002 );
    c.func( ); //调用 const版本的func()

   system( "PAUSE" );
   return 0;

}

另外,应该把不修改相应实参的形参定义为const引用,否则将限制该函数的使用,下面代码将产生编译错误:
string::size_type find_char(string &s, char c)
{
  while(i!=s.size()&&s[i]!=c) ++i;
  return i;
}
int main()
{
  find_char("Hello World", 'o') //error
  return 0;
}

        错误的原因:虽然字符串字面值传递给函数可以产生局部对象,但是这里形参被声明为引用,必须引用一个已存在的对象,所以上述代码才会导致编译错误。
        仅当形参是引用或指针时,形参是否为const才有重载现象。
class Account
{  };
void lookup(Account &)
{ }
void lookup(const Account &)
{ }      

void lookup3(Account *)
{ }
void lookup3( Account const*)
{ }
void lookup4(Account *) //错误,不能重载
{ }
void lookup4( Account *const)//错误,不能重载
{ } 

const Account a(0);
Account b;
lookup(a);  //call lookup(const Account &)
lookup(b);  //call lookup(Account &)

注意:不能基于指针本身是否为const来实现函数的重载。例如,
f(int *);
f(int *const);
以上两个函数无法构成重载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值