gpt4 book ai didi

c++ - 如何判断调用了哪个重载函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:24 25 4
gpt4 key购买 nike

#include <iostream>
#include <cmath>
using namespace std;

float f (int a, int b) {
return (a + b);
}

float f (float a, float b) {
return (round(a + b));
}

int main ()
{
cout << "Hello World!" << endl;
int int1 = 1;
int int2 = 2;
float float1 = 1.2f;
float float2 = 1.4f;
cout << f(int1, int2) << endl; // output: 3
cout << f(float1, float2) << endl; // output: 2
cout << f(int1, float2) << endl; // output: 2
return 0;
}
  1. 为什么最后一个输出使用f的第二个定义?

  2. 一般来说,当函数定义和函数调用之间的参数数量和类型不完全匹配时,如何确定将使用哪个重载函数定义?

    <

最佳答案

在尝试确定标准中为什么一个重载优先于另一个重载后,我得出的结论是不应该,在 f( int1 , float2 ) 并且代码不应编译。如果您的编译器接受它,则可能在实现中存在错误。

对于第二个问题,该标准定义了可用于匹配函数调用的转换,它还为那些用作部分排序的转换定义了一个等级(称为 em>比更好的转换)。编译器将始终选择最佳 转换,如果没有最佳 转换,则程序格式错误,如示例所示。

验证代码在不同编译器下的二义性:

海湾合作委员会:

conv.cpp:22: error: call of overloaded ‘f(int&, float&)’ is ambiguous
conv.cpp:5: note: candidates are: float f(int, int)
conv.cpp:9: note: float f(float, float)

clang :

conv.cpp:22:13: error: call to 'f' is ambiguous
cout << f(int1, float2) << endl; // output: 2
^
conv.cpp:5:7: note: candidate function
float f (int a, int b) {
^
conv.cpp:9:7: note: candidate function
float f (float a, float b) {
^

MSVS 2010(感谢 Xeo):

error C2666: 'f' : 2 overloads have similar conversions
src\main.cpp(2): could be 'void f(int,int)'
src\main.cpp(1): or 'void f(float,float)'
while trying to match the argument list '(int, float)'

关于c++ - 如何判断调用了哪个重载函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8689427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com