函数重载(overload)
C++函数重载机制
多个函数可以共享同一个函数名,针对不同的参数类型提供不同的操作
重载函数
如果同一个作用域内的几个函数名字相同但形参列表不同
void print(const int *b, const int *e){...}
void print(const int ia[], size_t size){...}
void print(const char *cp){...}
//调用重载函数时,编译器会根据实参的类型推断出要调用的是哪个函数
- 重载函数的参数表必须不同
- 或参数个数不同,或参数类型不同
- 返回类型不能区分两个重载函数
- 因为调用函数时可以忽略函数的返回值
int foo(int a);
int x = foo(5); //保存返回值
foo(10); //不保存返回值
void foo(int b); //错误声明
foo(10); //不能确定调用哪一个foo
const限定词对形参类型的影响
非指针和引用上的const限定词不区分重载函数
const限定指针或引用时,可以实现函数重载
// 同一函数的重复声明 int foo(int); //内置类型 int foo(const int); //同一函数的重复声明 //重载函数 void foo(string& str); //非const引用 void foo(const string& str); //const引用 int goo(int*); //非const引用 int goo(const int*); //const指针
重载函数的判断细则
一个函数名在某个作用域中多次声明时,编译器判断函数是否重载的规则:
| 参数表 | 默认实参 | 返回类型 | 是否重载 | 重复声明 | 重复定义 --------|---------|---------|---------|---------|---------| | NO | \ | \ | YES | \ | \ | | YES | \ | \ | \ | YES | \ | | YES | YES | \ | \ | ERROR | \ | | YES | NO | \ | \ | YES | \ | |const/volattile非指针或引用 | \ | \ | YES | |const/volattile指针或引用参数| YES | \ | \ |
//重载函数:参数类型不同
void print( int val );
void print( const string& );
//同一个函数的重复声明
void print( const string& s1);
void print( const string& s2);
//错误的重复声明
int print( int val );
void print( int val );
//同一个函数的重复声明
void max( int* ia, int az);
void max( int*, int = 10 );
//同一个函数的重复声明
void f ( int );
void f ( const int );
//重复定义错误
void f ( int ival ) {...}
void f ( const int ival ) {...}
//重载函数
void f ( int* );
void f ( const int* );
//重载函数
void f ( int& );
void f ( const int& );
重载函数的调用
- 调用函数时,如果存在多个重载函数,编译器将根据函数调用中指定的实参选择:
- 实参与形参的类型和个数匹配
- 隐式类型转换
- 调用结果
- 找到一个最佳匹配
- 找不到匹配,编译器错误:无匹配
- 找到多个匹配,编译器错误:二义性调用
最佳匹配的思想(匹配度等级)
- 不需要类型转换 >> 需要类型转换 , 实参形参匹配度高 > …形参实参匹配度低
- 函数参数个数相同且参数类型可以互相转换时,确定调用函数会困难一些