定义对象交换的函数模板(P332)
/*
函数模板与函数的区别:
1)函数模板本身在编译时不会生成任何目标代码,只有当通过模板生成具有的函数实例时才会生成目标代码。
2)被多个源文件引用的函数模板,应当连同函数体一同放在头文件中,而不能像普通函数那样只将声明放在头文件中。
3)函数指针也只能指向模板的实例,而不能指向模板本身。
*/
#include<iostream>
using namespace std;
template<class T> //类类型T
void Swap(T&x,T&y) //可以交换类对象
{
T tmp=x;
x=y;
y=tmp;
}
class myDate
{
public:
myDate();
myDate(int,int,int);
void printDate() const;
private:
int year,month,day;
};
myDate::myDate()
{
year=1970;
month=1;
day=1;
}
myDate::myDate(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void myDate::printDate()const
{
cout<<year<<"/"<<month<<"/"<<day;
return;
}
int main()
{
myDate a;
int n=1,m=2;
Swap(n,m);
a.printDate();
cout<<endl;
double f=1.2,g=2.3;
Swap(f,g);
a.printDate();
cout<<endl;
myDate d1,d2(2000,1,1);
Swap(d1,d2);
a.printDate();
cout<<endl;
return 0;
}

浙公网安备 33010602011771号