模板问题: 模板函数,模板类

1. 函数可以通过重载进行灵活调用,但是通用性仍不够.此时模板显得更加强大. 如下面所示.

//data.h进行声明
#include "stdio.h"
#include "iostream.h"
#include <string>
#if !defined(AFX_123)
int add(int,int);
template <class T1 t1,class T2 t2>
double add(T1,T2);


#define AFX_123
#endif

//data.cpp进行定义和调用
#include "data.h"
int add(int a,int b)
{
return (a+b);
}

double add(T1 t1,T2 t2)
{
return double(t1+t2)
}

void main()
{
int s1=add(2,3);
double s2=add(3.1415, 40.0);
}

2.类同样可以通过上述类似的方式定义模板类,使用等.

//data.h进行声明
#include "stdio.h"
#include "iostream.h"
#include <string>
#if !defined(AFX_123)

class CStudent
{
}

#define AFX_123
#endif

 

posted @ 2013-01-10 12:44  血洗女生宿舍  阅读(130)  评论(0编辑  收藏  举报