【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);//这个调用正确
当函数重载碰到默认参数,出现二义性,报错,所以尽量避免这种情况。
函数重载允许在同一个作用域内有同名但参数列表不同的函数,提高代码复用性。函数重载不依赖于返回类型,而是基于参数列表(类型、个数、顺序)。示例代码展示了不同参数类型的重载函数调用。引用和默认参数在重载中也起到作用,但默认参数可能导致二义性,应谨慎使用。
6076

被折叠的 条评论
为什么被折叠?



