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;
} 标准模版库里已经有了一个swap函数模板,你把自己写的swap换个名字就OK了 楼上正解,哈哈 楼上正解,哈哈
页:
[1]