模板怎么用?帮我把这个代码改一下.谢谢!

来源:百度知道 编辑:UC知道 时间:2024/05/06 12:14:14
// template1Hao.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
using namespace std;

template <typename T>

void swap(T& a,T& b)
{
T temp;
temp=a;
a=b;
b=temp;

}

int _tmain(int argc, _TCHAR* argv[])
{
int a=1,b=2;
cout<<swap(a,b)<<endl;;
cout<<"a is: "<<a<<"\nb is: "<<b<<endl;
return 0;
}
我按第一位的参考改了,还是有错误.
显示:
正在编译...
1>template1Hao.cpp
1>c:\users\a\documents\visual studio 2005\projects\template1hao\template1hao\template1hao.cpp(22) : error C2668: “swap”: 对重载函数的调用不明确
1> c:\users\a\documents\visual studio 2005\projects\template1hao\template1hao\template1hao.cpp(8): 可能是“void swap<int>(T &,T &)”
1> with
1>

你的函数swap名和标准库有冲突,改个名就行了。如myswap等。

#include "iostream"
using namespace std;

template <typename T>

void swap(T& a,T& b)
{
T temp;
temp=a;
a=b;
b=temp;

}

int _tmain(int argc, _TCHAR* argv[])
{
int a=1,b=2;
swap(a,b);
cout<<"a is: "<<a<<"\nb is: "<<b<<endl;
return 0;
}

二楼正解!