在C++ Primer中函数重载这一节讲到,为了确定最佳匹配,编译器将实参类型到相应形参的转换划分等级。转换等级以降序排列如下:
1.精确匹配。实参与形参类型相同
2.通过类型提升实现的匹配。
3.通过标准转换实现的匹配。
4.通过类类型转换的实现。
可是在下面的程序却发现,2的优先级甚至超过了1,十分不明白,所以先记下来,望大虾解答一下。
#include <iostream>
using namespace std;
//根据函数的参数列表不同而调用不同的函数
//一般来说,类型的提升优于类型的转换
void f(){ cout << "void f() is called!" << endl;}
void f(int a) {cout << "void f(int a) is called! " << endl;}
void f(double, double = 3.4){cout << "f(double, double = 3.4) is called! " << endl;}
int main()
{
//int i = 0;
//int j = 0;
//calc(i,j);
f(42, 2.6);
f(23);
return 0;
}
在VS08编译执行,结果如下所示:
f(double, double = 3.4) is called!
f(double, double = 3.4) is called!
本来结果,以本人猜想,后一个应该调用“void f(int a)”函数,结果出人意料,不知所以然。