2013.3.31 generic programing

泛型程序设计 generic programing

算法在实现十不指定具体要操作的数据类型的程序设计方法。

1.函数模板

template<class para1,class para2,...>

返回值类型 模板名(paras..){

   函数体;

}

 

e.g.

template<class T>

void swap(T &a,T &b){

  T temp = a;

  a = b;

  b = temp;

}


编译器由模板自动生成函数时。会用具体的类型名对模板中所有的类型参数进行替换。其他部分原封不动照抄。

此过程称为模板的实例化。得到模板函数!

 

新标准中的一个例子:

#include"iostream"
using namespace std;
/*
template<class T>
void print (const T array[],int size){
	int i ;
	for(i=0; i<size; i++){cout<<array[i];}
	return;
}
*/

void swap(int &x,int &y){
	int temp;
	temp = x;
	x = y;
	y = temp;

}



void swap2(int x,int y){
	int temp;
	temp = x;
	x = y;
	y = temp;
}


template<class T>
T MaxElement(T a[],int size){
	T max = a[0];
	int i;
	for(i=1; i<size; i++){
		if(a[i]>max){
			max = a[i];
		}
	
	}
	return max;
}

class CFraction
{
	
public:
	int num1,num2;
	CFraction(int n1,int n2):num1(n1),num2(n2){};
	bool operator > (const CFraction &f)const{
		if(num1*f.num2>0)
			return num1*f.num2>f.num1*num2;
		else
			return num1*f.num2<f.num1*num2;
	}
	bool operator == (const CFraction &f) const{
		return num1*f.num2 == num2*f.num1;
	}
	friend ostream &operator <<(ostream &o,const CFraction &f);
};

ostream &operator <<(ostream &o,const CFraction &f){
	o << f.num1 << "/" << f.num2;
	return o;
}	

int main(){
	
	int a[5]={1,2,3,4,5};
	CFraction f[4] = {CFraction(1,2),CFraction(1,4),CFraction(-5,7),CFraction(2,3)};
	cout<<MaxElement(a,5)<<endl;
	cout<<MaxElement(f,4)<<endl;
    
	return 0;

}

 

 

从上个例子可以看出,类型参数不但可以用来定义参数类型,还能用于定义局部变量和函数模板的返回值类型。

 

 

 

2.类模板

跟函数模板类似,当用到比较类似的类的时候可以使用

Template <para1>
class name1{
 ...members...
};

同样举个例子说明:

template<class T1,class T2>
class pair{
 T1 key;
 T2 value;
pair(T1 k,T2 v):key(k),value(v){};
};

int main(){
   pair<string ,int>student ("Tom",19);
   return 0;
}

同样有类模板的实例化,模板类的概念。

 

 

好吧 今天就到这里。明天继续!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值