【发布时间】:2013-01-22 10:33:06
【问题描述】:
#include <iostream>
#include <cmath>
using namespace std;
float f (int a, int b) {
return (a + b);
}
float f (float a, float b) {
return (round(a + b));
}
int main ()
{
cout << "Hello World!" << endl;
int int1 = 1;
int int2 = 2;
float float1 = 1.2f;
float float2 = 1.4f;
cout << f(int1, int2) << endl; // output: 3
cout << f(float1, float2) << endl; // output: 2
cout << f(int1, float2) << endl; // output: 2
return 0;
}
为什么最后一个输出使用
f的第二个定义?-
一般来说,当函数定义和函数调用之间的参数数量和类型不完全匹配时,如何确定将使用哪个重载函数定义?
李>
【问题讨论】:
-
我想你的意思是:
float float1 = 1.2;和float float2 = 1.4; -
我的直接答案是
int -> float比float -> int的转换效果更好。有趣的是,我无法在声明的标准中找到引用。 -
您使用的是什么编译器/版本?验证标准后,我认为代码应该会触发错误,因为调用
f( int1, float2 )是不明确。 GCC 和 Clang 同意。 -
MSVC(至少 10 个)实际上也同意。
标签: c++ overloading