x521079 发表于 2014-7-11 21:43:49

c++函数模板程序int类型出错误

#include<iostream>
#include<string>
using namespace std;
template<class T>
void swap(T &a, T &b)
{
   T tmp = a;
   a = b ;
   b = tmp ;
}

int main()
{
   int i1 = 100;
   int i2 = 200;
   
   cout << "交换前,i1 = "<< i1 << ",i2 = "<< i2 << "。\n";

   swap(i1,i2);    //int 和 double类型编译器都会报错 各种各样的报错英文,视频的一模一样却不报错
//cpp:19: error: call of overloaded `swap(int&, int&)' is ambiguous

   cout << "交换后,i1 = "<< i1 << ",i2 = "<< i2 << "。\n";
   
   string s1 = "小羊鱼";
   string s2 = "小鱿鱼";
   
   cout << "交换前,s1 = "<< s1 << ",s2 = "<< s2 << "。\n";
   swap(s1,s2);
   cout << "交换后,s1 = "<< s1 << ",s2 = "<< s2 << "。\n";
   
   return 0;
}

仰望天上的光 发表于 2014-7-11 23:30:01

标准模版库里已经有了一个swap函数模板,你把自己写的swap换个名字就OK了

戏++ 发表于 2014-7-12 12:40:05

楼上正解,哈哈

hfut_wangfei 发表于 2014-7-13 17:30:24

楼上正解,哈哈
页: [1]
查看完整版本: c++函数模板程序int类型出错误