您的位置:首页 > 编程语言 > C语言/C++

函数重载之const

2015-04-25 00:00 113 查看
我们知道,如果函数名相同,在相同的作用域内,其参数类型、参数个数,参数顺序不同等能构成函数重载。有趣的是如果同时在类中,对于函数名相同的const函数和非const函数能够构成重载,同时它们被调用的时机为:如果定义的对象是常对象,则调用的是const成员函数,如果定义的对象是非常对象,则调用重载的非const成员函数。例如:
#include <iostream>
using namespace std;
class A
{
public:
A( int x )
{
m = x;
}

int func( void )
{
cout << "non-[b]const[/b]" << endl;
m = 1700; //本函数体没有声明为[b]const,允许修改成员数据
[/b] return m;
}

//函数体限制为[b]const
[/b] int func( void )const
{
cout << "const" << endl;
return m;
}
private:
int m;
};

int main( void )
{
A b( 2002 );
b.func( ); //调用 非[b]const版本的func()
[/b]
const A c( 2002 );
c.func( ); //调用 [b]const版本的func()
[/b]
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);
以上两个函数无法构成重载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++