重载的"swap(float&, float&)"的调用是不明确的

call of overloaded 'swap(float&, float&)' is ambiguous

本文关键字:float 调用 不明确 重载 swap      更新时间:2023-10-16

在这个程序中,调用交换函数给出一个错误,称为调用overloded function是模棱两可的。请告诉我如何解决这个问题。 是否有任何不同的方法来调用模板函数

     #include<iostream>
    using namespace std;
      template <class T>
    void swap(T&x,T&y)
    {
            T temp;
            temp=x;
         x=y;
           y=temp;
       }
    int main()
   {
    float f1,f2;
    cout<<"enter twp float numbers: ";
    cout<<"Float 1: ";
     cin>>f1;
    cout<<"Float 2: ";
    cin>>f2;
    swap(f1,f2);
    cout<<"After swap: float 1: "<<f1<<" float 2:"<<f2;
    int a,b;
    cout<<"enter twp integer numbers: ";
    cout<<"int 1: ";
    cin>>a;
    cout<<"int 2: ";
    cin>>b;
    swap(a,b);
    cout<<"After swap: int 1: "<<a<<" int 2:"<<b;
    return 0;
    }

您的函数与某些包含隐式包含的 move.h 中定义的函数冲突。如果删除using namespace std则应解决此问题 - 与您冲突的函数是在 std 命名空间中定义的。

通过将交换

函数更改为my_swap函数,它解决了问题。 因为 swap 也是 C++ 中的预定义函数

#include<iostream>
using namespace std;
  template <class T>
void my_swap(T&x,T&y)
{
        T temp;
        temp=x;
     x=y;
       y=temp;
   }
int main()
{
  float f1,f2;
cout<<"enter twp float numbers: ";
cout<<"Float 1: ";
 cin>>f1;
cout<<"Float 2: ";
cin>>f2;
my_swap(f1,f2);
cout<<"After swap: float 1: "<<f1<<" float 2:"<<f2;
int a,b;
cout<<"enter twp integer numbers: ";
cout<<"int 1: ";
cin>>a;
cout<<"int 2: ";
cin>>b;
my_swap(a,b);
cout<<"After swap: int 1: "<<a<<" int 2:"<<b;
return 0;
}

当然,重命名您的函数或删除 ->库中已经有一个:

http://www.cplusplus.com/reference/algorithm/swap/

这就是您的编译器所抱怨的。