C++中的函数重载。不适用于 float,适用于 double
Function overloading in C++. Does not work with float, works with double
#include <iostream>
using namespace std;
int square(int x);
float square(float x);
int main() {
cout<<square(3);
cout<<square(3.14);
return 0;
}
int square(int x) {
cout<<"\nINT version called\n";
return x*x;
}
float square(float x) {
cout<<"\nFLOAT version called\n";
return x*x;
}
我试过用double one替换一个函数的float版本,然后它开始工作了。这里有什么问题? 3.14不能算float吗?
error: call of overloaded 'square(double)' is ambiguous
note: candidates are:
note: int square(int)
note: float square(float)
C++ 中的浮点文字属于 double
类型。从 double
到 int
和 float
的转换没有定义顺序,因此您的调用不明确。
如果要调用 float
函数,请使用 float
文字调用它:
cout<<square(3.14f);
//note the f here^
3.14 被编译器当作双精度数。它没有找到带有 double 参数的函数,如果它应该将 double 转换为 int 或 float 会感到困惑。因此要么尝试下面的代码,要么在函数声明中使用 double。
cout<<square(3.14f);
#include <iostream>
using namespace std;
int square(int x);
float square(float x);
int main() {
cout<<square(3);
cout<<square(3.14);
return 0;
}
int square(int x) {
cout<<"\nINT version called\n";
return x*x;
}
float square(float x) {
cout<<"\nFLOAT version called\n";
return x*x;
}
我试过用double one替换一个函数的float版本,然后它开始工作了。这里有什么问题? 3.14不能算float吗?
error: call of overloaded 'square(double)' is ambiguous
note: candidates are:
note: int square(int)
note: float square(float)
C++ 中的浮点文字属于 double
类型。从 double
到 int
和 float
的转换没有定义顺序,因此您的调用不明确。
如果要调用 float
函数,请使用 float
文字调用它:
cout<<square(3.14f);
//note the f here^
3.14 被编译器当作双精度数。它没有找到带有 double 参数的函数,如果它应该将 double 转换为 int 或 float 会感到困惑。因此要么尝试下面的代码,要么在函数声明中使用 double。
cout<<square(3.14f);