/***********************************************
template即模板,class指类别,T是类别的统称,
可以使int、char,float,double等等。
在PrintArray打印各数时,当参数是a,则T为int,
当参数是b,则T为double,当参数是c,则T为char。
PrintArray就是模板名。
************************************************/
#include <iostream>
using namespace std;
template<class T>
void PrintArray(T *Array,int count)
{
for(int i=0;i<count;i++)
cout<<Array[i]<<" ";
cout<<endl;
}
int main()
{
int a[5]={1,2,3,4,5};
double b[7]={1.1,2.2,3.3,4.4,5.5,6.6,7.7};
char c[6]="HELLO";
PrintArray(a,5);
PrintArray(b,7);
PrintArray(c,6);
return 0;
}
/*
1 2 3 4 5
1.1 2.2 3.3 4.4 5.5 6.6 7.7
H E L L O
#include <stdio.h>
void print(int *p, int len)
{
int i;
for(i = 0; i < len; i++){
printf("%d ", p[i]); // *(p+i)
}
printf("\n");
}
int main(void)
{
int num[3] = {1,2,3};
print(num, 3);
return 0;
}
akaedu@akaedu-G41MT-D3:~$ ./a.out
1 2 3
*/
<pre name="code" class="cpp">/*******************************************************
RN(int _x=1,int _y=1):x(_x),y(_y){}
//RN::RN(int _x = 1, int _y = 1):x(_x),y(_y){}
RN::RN(int _x = 1, int _y = 1){
x = _x;
y = _y;
}
####Stack<T>& operator =(const Stack<T>& rightSide);
template <class T>
void print_array(T *buf, size_t n){
for(int i=0; i<n; i++)
buf[i].print();
}
********************************************************/
#include <iostream>
using namespace std;
class RN{
public:
RN(int _x=1,int _y=1):x(_x),y(_y){}
bool operator >(RN rn)const{
return x/(double)y > rn.x/(double)rn.y;
}
void print()const{
cout << x << "/" << y << endl;
}
private:
int x,y;
};
/*
//RN::RN(int _x = 1, int _y = 1):x(_x),y(_y){}
RN::RN(int _x = 1, int _y = 1){
x = _x;
y = _y;
}
*/
class xpoint{
public:
xpoint(int _x=0,int _y=0):x(_x),y(_y){}
bool operator >(xpoint p)const {
return x^2+y^2 > p.x^2+p.y^2;
}
void print()const{
cout << x << "," << y << endl;
}
private:
int x,y;
};
template <class T>
void print_array(T *buf, size_t n){
for(int i=0; i<n; i++)
buf[i].print();
}
template <class T>
void sort(T *a, size_t len){
T t;
for(int i=0; i<len-1; i++) /* 冒泡法排序 */
for(int j=0; j<len-i-1; j++)
if(a[j]>a[j+1]) {
t=a[j];/* 交换a[i]和a[j] */
a[j]=a[j+1];
a[j+1]=t;
}
}
int main(){
xpoint x[10]={xpoint(1,3),xpoint(2,2),xpoint(4,4)};
sort(x,10);
print_array(x,10);
}
/*$ ./a.out
0,0
0,0
0,0
0,0
0,0
0,0
0,0
2,2
1,3
4,4
*/
template<class T>
最新推荐文章于 2024-05-15 08:56:34 发布