函数模板:“函数体相同,数据类型不同,模板!”
变量的引用:“你我同为一体,一荣俱荣,一损俱损”
#include <iostream>
using namespace std;template <typename numtype>
void swap(numtype &a,numtype &b)
{
numtype &temp=a;
a=b;
b=temp;
}
int main()
{
int g=6,h=7;
swap(g,h);
cout<<g<<' '<<h<<endl;
float c=6.1,d=7.1;
swap(c,d);
cout<<c<<' '<<d<<endl;
return 0;
}
当我把变量的引用和函数模板结合起来用的时候,编译器是这么提示我语法错误的:
error: call of overloaded 'swap(int&, int&)' is ambiguous
error: call of overloaded 'swap(float&, float&)' is ambiguous
当我把指针和函数模板结合起来用的时候,顺利通过了编译,程序运行结果正确:
#include <iostream>
using namespace std;
template <typename numtype>
void swap(numtype *a,numtype *b)
{
numtype *temp=a;
a=b;
b=temp;
}
int main()
{
int g=6,h=7;
swap(g,h);
cout<<g<<' '<<h<<endl;
float c=6.1,d=7.1;
swap(c,d);
cout<<c<<' '<<d<<endl;
return 0;
}
记下了,当作踏入c++沼泽的第二脚。