[英]Why does this program in c++, visual studio code shows error
//function overloading
#include <iostream>
using namespace std;
//declaration of function protype
int area(int);
int area(int, int);
float area(float);
int main()
{
cout << "calling the area() function for computiong the area of a square (side=5) - " << area(5) << "\n";
cout << "calling the area() function for computiong the area of a rectangle (length = 5, bredth = 10) - " << area(5, 10) << "\n";
cout << "calling the area() function for computiong the area of a cirlce (radius 5.5) - " << area(5.5) << "\n";
return 0;
}
int area(int side)
{
return (side * side);
}
int area(int length, int breadth)
{
return (length * breadth);
}
float area(float radius)
{
return (3.14 * radius * radius);
}
error错误
program4_5.cpp: In function 'int main()':
program4_5.cpp:14:106: error: call of overloaded 'area(double)' is ambiguous
14 | cout << "calling the area() function for computiong the area of a cirlce (radius 5.5) - " << area(5.5) << "\n";
| ^
program4_5.cpp:6:5: note: candidate: 'int area(int)'
6 | int area(int);
| ^~~~
program4_5.cpp:8:7: note: candidate: 'float area(float)'
8 | float area(float);
| ^~~~
PS C:\Users\hasht\Desktop\coding\OOP with c++>
this code while compiling shows function overloading error but from what I know it's correct as I have defined the float area( float radius) function.此代码在编译时显示 function 过载错误,但据我所知,这是正确的,因为我已经定义了浮动区域(浮动半径)function。 Can anyone explain why this error occurs.
谁能解释为什么会发生此错误。 I am new to coding and i don't know how to fix this.
我是编码新手,我不知道如何解决这个问题。
5.5
is a literal of type double
, so the compiler doesn't know you want to call the overload taking an int
or the one taking a float
. 5.5
是double
类型的文字,因此编译器不知道您要调用采用int
的重载还是采用float
的重载。
You can use a float
-literal instead:您可以使用
float
-literal 代替:
// -V-
cout << "..." << area(5.5f) << "\n";
Type area(5.5f)
to force the value to be a float.键入
area(5.5f)
以强制该值为浮点数。
The compiler does not know if it should cast your double value to an int or a float.编译器不知道它是否应该将您的双精度值转换为 int 或 float。 Therefore, it is ambiguous.
因此,它是模棱两可的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.