参数缺省值只能出现在函数的声明中,而不能出现在定义体中 。
1 #include <iostream> 2 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 4 using namespace std; 5 //声明函数模板的原型语句 6 template <class T> void swap(T *x, T *y); 7 8 //定义一个结构类型 9 struct student { 10 int n; 11 char name[20]; 12 float grade; 13 }; 14 15 int main(int argc, char** argv) { 16 //交换两个int型变量中的数据 17 int m=3,n=5; 18 cout<<"m="<<m<<" n="<<n<<endl; 19 swap(&m,&n); 20 cout<<"m="<<m<<" n="<<n<<endl; 21 cout<<"-------------------"<<endl; 22 23 //交换两个double型变量中的数据 24 double x=3.5,y=5.7; 25 cout<<"x="<<x<<" y="<<y<<endl; 26 swap(&x,&y); 27 cout<<"x="<<x<<" y="<<y<<endl; 28 cout<<"-------------------"<<endl; 29 30 //交换两个char型变量中的数据 31 char c1='A',c2='a'; 32 cout<<"c1="<<c1<<" c2="<<c2<<endl; 33 swap(&c1,&c2); 34 cout<<"c1="<<c1<<" c2="<<c2<<endl; 35 cout<<"-------------------"<<endl; 36 37 //交换两个结构变量中的数据 38 student s1={1001,"ZhangHua",90}; 39 student s2={1011,"LiWei",95.5}; 40 cout<<"s1: "; 41 cout<<s1.n<<" "<<s1.name<<" "<<s1.grade<<endl; 42 cout<<"s2: "; 43 cout<<s2.n<<" "<<s2.name<<" "<<s2.grade<<endl; 44 45 swap(&s1,&s2); 46 cout<<"swap(s1,s2):"<<endl; 47 cout<<"s1: "; 48 cout<<s1.n<<" "<<s1.name<<" "<<s1.grade<<endl; 49 cout<<"s2: "; 50 cout<<s2.n<<" "<<s2.name<<" "<<s2.grade<<endl; 51 return 0; 52 } 53 54 55 56 //定义名为swap的函数模板用于交换两个变量中的数据 57 template <class T> void swap(T *x, T *y) 58 { 59 T temp; 60 temp=*x; 61 *x=*y; 62 *y=temp; 63 }