概念
函数重载,术语为“多态”,指的是同名函数有多种形式,他们完成相同的工作,但使用不同的参数列表。
函数重载的关键是函数的参数列表——也称为函数的特征标(function signature)。
C++允许定义名称相同的函数,条件是他们的特征标即函数的参数列表不同。如
void print(const char * str,int width);
void print(double d,int width);
void print(long l,int width);
注意
- 在编译器编译时,编译器将根据对应的实参匹配对应的函数原型,若不与任何原型匹配,并不会停止使用其中的某个函数,因为C++将尝试使用标准类型转换进行匹配,若有多种转换的方式,C++将拒绝这种函数调用,将其视为错误。
- 编译器在检查函数特征标时,将把类型引用和类型本身视为同一个特征标。
double cube(double x); double cube(double & x);
参数x与double x原型和double & x原型都匹配,因此编译器无法确定究竟应使用哪个原型。
-
匹配函数时,并不区分const和非const变量,但区分const和非const指针和引用。
#include <iostream> using namespace std; void dribble_1(char *bits) { cout << "success char *bits" << endl; } void dribble_1(const char *bits) { cout << "success const char *bits" << endl; } void dribble_2(char &bits) { cout <<"success char &bits" << endl; } void dribble_2(const char &bits) { cout << "success const char &bits" << endl; } /*void dribble_3(char bits) { cout << "success char bits" << endl; } void dribble_3(const char bits) { cout << "success const char bits" << endl; }*/ int main(void) { const char const_c = 'a'; char c = 'b'; const char* const_cc = &const_c; char * cc = &c; dribble_1(const_cc); dribble_1(cc); dribble_2(const_c); dribble_2(c); //dribble_3(const_c); //dribble_3(c); return 0; }
输出结果为
success const char *bits success char *bits success const char &bits success char &bits
可见在指针与引用时,编译器将根据实参是否为const来决定使用哪个原型。当形参有const时,实参可以是const或者非const,当形参没有const时,实参不能有const。
#include <iostream> using namespace std; void dribble_3(char bits) { cout << "success char bits" << endl; } void dribble_3(const char bits) { cout << "success const char bits" << endl; } int main(void) { const char const_c = 'a'; char c = 'b'; dribble_3(const_c); dribble_3(c); return 0; }
编译报错情况如下
||=== Build file: "no target" in "no project" (compiler: unknown) ===| F:\codeblocks_file\test\overloaded.cpp|8|error: redefinition of 'void dribble_3(char)'| F:\codeblocks_file\test\overloaded.cpp|4|note: 'void dribble_3(char)' previously defined here| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
从报错可以看出,当形参类型为变量时,有无const并不能做到重载函数,即匹配函数时,并不区分const和非const变量,但区分const和非const指针和引用。
补充:当形参为变量的时候,在进行函数调用的时候,使用的时实参的副本,即值传递 ,此时无论变量是否为const,传递的都是它的副本,与实参原来的类型无关,所以有无const的情况是一样的。
#include <iostream> using namespace std; void dribble_3(char bits) { cout << "success char bits" << endl; } /*void dribble_3(const char bits) { cout << "success const char bits" << endl; }*/ int main(void) { const char const_c = 'a'; char c = 'b'; dribble_3(const_c); dribble_3(c); return 0; }
success char bits success char bits
-
注意重载函数的特征标必须不同,与函数类别无关,即函数类别不同但特征标相同并不满足重载。
long gronk(int n,float m); double gronk(int n,float m); //same signatures,hence not allowed
何时使用函数重载
当函数基本上执行相同的任务,但是用不同形式的数据时,才应使用函数重载。