c++中的函数重载不起作用

function overloading in c++ not working

本文关键字:重载 不起作用 函数 c++      更新时间:2023-10-16

当我运行这个程序时,它会产生错误[Error] call of overloaded 'add(double, double, double)' is ambiguous

为什么?我的意思是,函数参数有不同的数据类型,这实际上是函数重载,那么为什么会出错呢?

然而,当浮子被双浮子取代时,它工作得很好。

#include<iostream>
using namespace std;
    void add(){
       cout<<"I am parameterless and return nothing";
    }
    int add( int a, int b ){
        int z = a+b;
        return z;
    }
    int add(int a, int b, int c){
         int z = a+b+c;
         return z;
    }
   int add(float a, float b, float c)
    {
         int z = a +b + c;
         return z;
    }
int main()
{
   cout<<"The void add() function -> ";
   add();
   cout<<endl;
   cout<<"add(2,3) -> "<<add(2,3)<<endl;
   cout<<"add(2,3,4) -> "<<add(2,3,4)<<endl;
   cout<<"add(2.1,4.5) -> "<<add(2.8,3.1,4.1)<<endl;
   return 0;
}

因为使用double文本调用函数,而这些函数可以转换为int转换为float,编译器不知道应该选择哪个。

最简单的解决方案是使用float文字来调用函数:

add(2.8f,3.1f,4.1f)