理解 C++ 中的函数重载歧义:Double 平方与 Float 参数

问题描述 投票:0回答:1

考虑以下程序,该程序基于 Deitel C 如何编程书中的示例。

// funOverloading.cpp

#include <iostream>
using namespace std;

// function square for int values
int square( int x )
{ 
   cout << "square of integer " << x << " is ";
   return x * x; 
}

// function square for float values
float square( float y ) 
{ 
   cout << "square of float " << y << " is ";
   return y * y; 
}

int main()
{
   cout << square( 7 ); // calls int version
   cout << endl;
   cout << square( 7.5 ); // calls float version
   cout << endl;
}  

因为 CPP 默认将 7.5 视为 double 而不是 float,因此由于没有 float 参数采用 sqaure 函数,程序应该会导致编译器错误,应该显示类似的内容

no overloaded function found for the function call 'square( 7.5 )' in 
cout << square( 7.5 ); // calls float version

但是在运行时,我实际上收到以下错误:

funOverloading.cpp: In function 'int main()':
funOverloading.cpp:24:18: error: call of overloaded 'square(double)' is ambiguous
   24 |    cout << square( 7.5 ); // calls float version
      |            ~~~~~~^~~~~~~
funOverloading.cpp:7:5: note: candidate: 'int square(int)'
    7 | int square( int x )
      |     ^~~~~~
funOverloading.cpp:14:7: note: candidate: 'float square(float)'
   14 | float square( float y )
      |       ^~~~~~

从这个错误可以看出,编译器尝试调用“square(7.5)”,但由于无法在 sqaure 的 float 和 int 版本之间进行选择而失败。事实上,如果我们没有 float square 定义,编译器将不会给出任何错误,甚至根本不会给出警告。检查这里

我有两个问题,首先为什么编译器不关心 7.5 是双精度数并且不会引发错误,即使编译器确实尝试调用“square(7.5)”,为什么它不简单地选择浮点数版本?我的意思是双精度数更像是浮点数而不是整数。

c++ function overloading
1个回答
0
投票

出现问题是因为文字

7.5
double
,因此,它可以转换为
float
OR
int
,具有同等优先级。

如果您添加

double
重载或者您的文字更具体,例如,您就不会遇到此问题:

int main()
{
   cout << square( 7 ); // calls int version
   cout << endl;
   cout << square( 7.5F ); // calls float version
   cout << endl;
}

https://godbolt.org/z/1xncafn51

PS:使用更好的 C++ 书籍 权威的 C++ 书籍指南和列表

© www.soinside.com 2019 - 2024. All rights reserved.