函数重载也称为方法重载。函数重载是多态性概念所提供的功能,它已在面向对象的编程中广泛使用。
为了实现函数重载,函数应满足以下条件:
函数的返回类型应该相同
功能名称应相同
参数的类型可以不同,但数量应相同
int display(int a); int display(float a); // both the functions can be overloaded int display(int a); float display(float b); //both the functions can’t be overloaded as the return type of one function is different from another
具有不同名称和不同参数数量的功能
#include<iostream>
using namespace std;
int max_two(int a, int b) //contains two parameters{
if(a>b){
return a;
}
else{
return b;
}
}
int max_three(int a, int b ,int c) //contains three parameters{
if (a>b && a>c){
return a;
}
else if(b>c){
return b;
}
else{
return c;
}
}
int main(){
max_two(a,b);
return 0;
}具有相同名称但返回类型不同的函数
#include<iostream>
using namespace std;
int max_two(int a, int b){
if(a>b){
return a;
}
else{
return b;
}
}
float max_two(int a, int b){
if(a>b){
return a;
}
else{
return b;
}
}
int main(){
max_two(a, b);
return 0;
}成员函数满足函数重载的所有条件,但如果它是静态成员函数,则不能重载。
#include<iostream>
class check{
static void test(int i)
{ }
void test(int i)
{ }
};
int main(){
check ch;
return 0;
}如果两个函数完全相同,但仅在默认参数上有所不同,即其中一个函数包含默认参数,则它们被视为相同,这意味着它们不能重载,因此编译器将抛出重新声明同一函数的错误。
#include<iostream>
#include<stdio.h>
using namespace std;
int func_1 ( int a, int b){
return a*b;
}
int func_1 ( int a, int b = 40){
return a+b;
}
Int main(){
func_1(10,20);
return 0;
}