簡體   English   中英

為什么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++> 

此代碼在編譯時顯示 function 過載錯誤,但據我所知,這是正確的,因為我已經定義了浮動區域(浮動半徑)function。 誰能解釋為什么會發生此錯誤。 我是編碼新手,我不知道如何解決這個問題。

5.5double類型的文字,因此編譯器不知道您要調用采用int的重載還是采用float的重載。

您可以使用float -literal 代替:

//                      -V-
cout << "..." << area(5.5f) << "\n";

鍵入area(5.5f)以強制該值為浮點數。

編譯器不知道它是否應該將您的雙精度值轉換為 int 或 float。 因此,它是模棱兩可的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM