寻找合适的重载函数:
1、候选函数,即同名的函数重载函数
2、可行的函数,即候选函数中,形式参数与实参个数和类型相同的,这里的类型相同并不是严格意义上的相同,包含了可以转化的类型
3、从可行函数中选出最佳匹配函数,如果不存在唯一的最佳匹配函数,那么调用会失败。
c++ primer中认为最佳的匹配函数满足下面两个条件:
(1)The match for each argument is no worse than the match required by any other viable function
(2)There is at least one argument for which the match is better than the match provided by any other viable function
举几个简单的例子:
(1)
#include <iostream>
#include <string>
using namespace std;
void f(int x ,int y)
{
cout << x << y << endl;
}
void f(double x,double y)
{
cout << x << y << endl;
}
int main()
{
int x=8;
int y=9;
f(x,y);
system("pause");
}
这个例子中,第一个函数的参数都是int,第二个都是double。精确匹配的要好于需要类型转换的,所以第一个函数是最佳匹配函数
(2)
#include <iostream>
#include <string>
using namespace std;
void f(int x ,int y)
{
cout << x << y << endl;
}
void f(double x,double y)
{
cout << x << y << endl;
}
int main()
{
int x=8;
double y=9.0;
f(x,y);
system("pause");
}
这个就会编译失败,因为从第一个参数来讲,第一个函数不需要类型转换,从第二个函数将,第二个参数也不要类型转换。所以这两个半斤八两吧,区分不出水最佳。
(3)
#include <iostream>
#include <string>
using namespace std;
void f(int x ,int y,int z)
{
cout << x << y << endl;
}
void f(double x,double y,double z)
{
cout << x << y << endl;
}
int main()
{
int x=8;
int y=9;
double z =9.09;
f(x,y,z);
system("pause");
}
这个竟然也不能编译通过,有点搞不懂