为什么这个程序在c++中,visual studio代码显示错误
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);
}
错误
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++>
此代码在编译时显示函数重载错误,但据我所知它是正确的,因为我已经定义了浮动区域(浮动半径)函数。任何人都可以解释为什么会出现此错误。我是编码新手,我不知道如何解决这个问题。
键入 area(5.5f)
以强制该值为浮点数。
编译器不知道是否应将您的双精度值转换为 int 或 float。因此,它是模棱两可的。
5.5
是 double
类型的文字,因此编译器不知道您要调用采用 int
的重载还是采用 [=14= 的重载].
您可以改用 float
-文字:
// -V-
cout << "..." << area(5.5f) << "\n";
//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);
}
错误
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++>
此代码在编译时显示函数重载错误,但据我所知它是正确的,因为我已经定义了浮动区域(浮动半径)函数。任何人都可以解释为什么会出现此错误。我是编码新手,我不知道如何解决这个问题。
键入 area(5.5f)
以强制该值为浮点数。
编译器不知道是否应将您的双精度值转换为 int 或 float。因此,它是模棱两可的。
5.5
是 double
类型的文字,因此编译器不知道您要调用采用 int
的重载还是采用 [=14= 的重载].
您可以改用 float
-文字:
// -V-
cout << "..." << area(5.5f) << "\n";