Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1589686
  • 博文数量: 695
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 4027
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-20 21:22
文章分类

全部博文(695)

文章存档

2018年(18)

2017年(74)

2016年(170)

2015年(102)

2014年(276)

2013年(55)

分类: C/C++

2014-08-27 20:38:08

函数重载之const     我们知道,如果函数名相同,在相同的作用域内,其参数类型、参数个数,参数顺序不同等能构成函数重载。有趣的是如果同时在类中,对于函数名相同的const函数和非const函数能够构成重载,同时它们被调用的时机为:如果定义的对象是常对象,则调用的是const成员函数,如果定义的对象是非常对象,则调用重载的非const成员函数。例如:

#include 
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的引用只能绑定同类型的对象)
        仅当形参是引用或指针时,形参是否为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);
 以上两个函数无法构成重载。

阅读(1080) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~