C++函数重载
函数重载是指函数名在满足一定的条件下可以相同,这样做的作用是能够提高代码的复用性,同一个函数名在不同的条件下可以有不同的功能。
须满足的条件:
- 函数位于同一个作用域下
- 函数名称相同
- 函数参数类型不同或者个数不同或者顺序不同
案例一:参数个数不同
#include<iostream>
using namespace std;
void func() //函数中参数个数为0
{
cout << "函数1" << endl;
}
void func(int a) //函数中参数个数为1
{
cout << "函数2" << endl;
}
int main()
{
int a = 5;
func();
func(a);
system("pause");
return 0;
}
结果:两次调用的函数名虽然相同,但是由于参数的个数不同,调用到了不同的函数。
案例二:参数类型不同
#include<iostream>
using namespace std;
void func(int a) //参数的数据类型是整型
{
cout << "函数1" << endl;
}
void func(float a) //参数的数据类型是浮点型
{
cout << "函数2" << endl;
}
int main()
{
int a = 5;
float b = 5.5;
func(a);
func(b);
system("pause");
return 0;
}
结果:两次调用的函数名虽然相同,但是由于参数的数据类型不同,调用到了不同的函数。
案例三:参数顺序不同
#include<iostream>
using namespace std;
void func(int a,float b) //整型在前,浮点型在后
{
cout << "函数1" << endl;
}
void func(float a,int b) //浮点型在前,整型在后
{
cout << "函数2" << endl;
}
int main()
{
int a = 5;
float b = 5.5;
func(a,b);
func(b,a);
system("pause");
return 0;
}
结果:两次调用的函数名虽然相同,但是由于参数的顺序不同,调用到了不同的函数。
注意事项
函数的返回值不可以作为函数重载的条件
int func() //函数的返回值类型为整型
{
cout << "函数1" << endl;
}
float func() //函数的返回值类型为浮点型
{
cout << "函数2" << endl;
}
这样的两个函数不能构成重载,运行时编译器会报错。