error: call of overloaded ‘swap(int&, int&)’ is ambiguous

代码:  

 #include<iostream>
   using namespace std;
   template <class T>
  void swap(T&a, T&b) {
       T tmp = a;
       a = b;
       b = tmp;
   }
   int main()
  {
      int a = 3, b = 30;
      swap(a, b);
      cout<<"a = "<<a<<"  b = "<<b;
      cout<<endl;
      float x = 1.2,y = 6.8;
      swap(x, y);
      cout<<"x = "<<x<<"  y = "<<y;                                                                                                                                                                             
      cout<<endl;
      double q = 1, p = 2;
      swap(q, p);
      cout<<"q = "<<q<<"  p = "<<p;
      cout<<endl;
      return 0;
 }

编译:

原因:c++自己提供了swap,因此在编译的时候会报错:这个重载是分不清的。

  1 #include<iostream>
  2 using namespace std;
  3 template <class T>
  4 void Swap(T&a, T&b) {
  5     T tmp = a;
  6     a = b;
  7     b = tmp;
  8 }
  9 int main()
 10 {
 11     int a = 3, b = 30;
 12     Swap(a, b);
 13     cout<<"a = "<<a<<"  b = "<<b;
 14     cout<<endl;
 15     float x = 1.2,y = 6.8;
 16     Swap(x, y);
 17     cout<<"x = "<<x<<"  y = "<<y;
 18     cout<<endl;
 19     double q = 1, p = 2;
 20     swap(q, p);                                                                                                                                                                                                                         
 21     cout<<"q = "<<q<<"  p = "<<p;
 22     cout<<endl;
 23     return 0;
 24 }

运行结果

发布了25 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39771637/article/details/102701241