C++支持函数重载
- 当用户调用函数时,只需要在参数表中带入实参,编译器就会根据实参的类型来确定到底哪个函数重载。
注:函数重载的二义性问题!!
- 支持函数重载:函数名相同,但参数的个数或参数的类型不同(等)。以这两种情况为例,如下:
(1)参数个数相同,参数类型不同,支持函数重载:
#include <iostream>
using namespace std;
int square(int i)
{return i*i;}
float square(float f)
{return f*f;}
double square(double d)
{return d*d;}
int main()
{
int i=2;
float f=2.3;
double d=3.45;
cout<<square(i)<<endl; // 4
cout<<square(f)<<endl; // 5.29
cout<<square(d)<<endl; // 11.9025
return 0;
}
(2)参数个数不同,参数类型相同,支持函数重载:
#include <iostream>
using namespace std;
int mul(int x,int y)
{return x*y;}
int mul(int x,int y,int z)
{return x*y*z;}
int main()
{
int a=1,b=2,c=3;
cout << mul(a,b) << endl; // 2
cout << mul(a,b,c) << endl;// 6
}