【C++】函数重载
函数重载的作用:函数名相同,提高复用性。
函数重载满足的条件:
- 同一个作用域下;
- 函数名称相同;
- 函数参数 类型不同 或者 个数不同 或者 顺序不同。
【注意】函数的返回值不可以作为函数重载的条件。
【代码示例】
#include <iostream>
using namespace std;
void func(){
cout<<"func()"<<endl;
}
void func(int a){
cout<<"func(int a)"<<endl;
}
void func(double a){
cout<<"func(double a)"<<endl;
}
void func(int a, double b){
cout<<"func(int a, double b)"<<endl;
}
void func(double a, int b){
cout<<"func(double a, int b)"<<endl;
}
int main(){
func();
func(10);
func(3.14);
func(10, 3.14);
func(3.14, 10);
return 0;
}
【注意事项】
- 引用作为函数重载条件
void func(int& a){
cout<<"func(int& a)"<<endl;
}
void func(const int& a){
cout<<"func(const int& a)"<<endl;
}
int a=20;
func(10);//调用func(const int& a)
func(a);//调用func(int& a)
- 函数重载碰到默认参数
void func2(int a, int b=10){
cout<<"func(int a, int b)"<<endl;
}
void func2(int a){
cout<<"func(int a)"<<endl;
}
//调用func2(10);会报错
func2(10, 20);//这个调用正确
当函数重载碰到默认参数,出现二义性,报错,所以尽量避免这种情况。