模板函数

来源:互联网 发布:js杀破狼歌曲下载 编辑:程序博客网 时间:2024/06/05 20:23
下面的代码不管是在VC6.0还是在VC2010上都是不通过,为什么啊,知道的说下:
听君一席话,胜读十年书
#include<iostream>
using namespace std;
template <typename T>
void swap(T &a,T &b);
struct KT

{

char name[40];

double xinshui;

int floor;

};

template <>void swap<KT>(KT &kt1,KT &kt2);
void show(KT &kt);

int main()
{

system ("color d");

int i=10,j=20;

cout<<"没用模板之前:\n";

cout<<"i="<<i<<",j="<<j<<endl;

swap(i,j);

cout<<"使用模板之后:\n";

cout<<"i="<<i<<",j="<<j<<endl;

KT mzx={"mazxiao",4324.56,3};

KT yys={"yyansheng",4200.78,5};

cout<<"没用模板之前:\n";

show(mzx);

show(yys);

cout<<"使用模板之后:\n";

show(mzx);

show(yys);

return 0;

}
template <typename T>
void swap(T &a,T &b)
{

T t;

t=a;

a=b;

b=t;
}
template <>void swap<KT>(KT &kt1,KT &kt2)
{

double t1;

int t2;

t1=kt1.xinshui;

kt1.xinshui=kt2.xinshui;

kt2.xinshui=t1;

t2=kt1.floor;

kt1.floor=kt2.floor;

kt2.floor=t2;
}
void show(KT &kt)
{

cout<<"姓名:"<<kt.name<<endl;

cout<<"薪水:"<<kt.xinshui<<endl;

cout<<"工作层:"<<kt.floor<<endl;
}
/*
--------------------Configuration: Cpp1 - Win32 Debug--------------------
Compiling...
Cpp1.cpp
C:\Windows\System32\Cpp1.cpp(20) : error C2667: 'swap' : none of 2 overload have a best conversion
C:\Windows\System32\Cpp1.cpp(20) : error C2668: 'swap' : ambiguous call to overloaded function
C:\Windows\System32\Cpp1.cpp(23) : error C2078: too many initializers
C:\Windows\System32\Cpp1.cpp(24) : error C2078: too many initializers
执行 cl.exe 时出错.

Cpp1.exe - 1 error(s), 0 warning(s)
*/