/* 模板函数 */
/* minmax.h */
//#pragma interface //新版gnu c++ 不需要此条语句
template
//T是类型占位符,class 可以指任何数据类型
//不一定是指c++ 类
T max(T a, T b)
{
if (a > b)
return a;
else
return b;
}
template
T min(T a, T b)
{
if (a < b)
return a;
else
return b;
}
/* tminmax.cpp */
#include
//#pragma implementation "minmax.h"
#include "minmax.h"
//using namespace std; //使用标准名空间会有重名错误
//instatiate template functions
template int min(int, int);
template double min(double, double);
template char min(char, char);
template int max(int, int);
template double max(double, double);
template char max(char, char);
int main()
{
int i1 = 100, i2 = 200;
double d1 = 3.14159, d2 = 9.87654;
char c1 = 'A', c2 = 'z';
cout << "max(i1, i2) == " << max(i1, i2) << endl;
cout << "max(d1, d2) == " << max(d1, d2) << endl;
cout << "max(c1, c2) == " << max(c1, c2) << endl;
cout << "min(i1, i2) == " << max(i1, i2) << endl;
cout << "min(d1, d2) == " << max(d1, d2) << endl;
cout << "min(c1, c2) == " << max(c1, c2) << endl;
return 0;
}
模板类的定义使用。。
/* db.h */
/*
* 模板类
*/
#include
using namespace std;
class DBError {
private:
string msg;
public:
DBError(const string &msg_arg):msg(msg_arg) { }
const string &what()const { return msg; }
};
template
class TDatabase {
private:
T *rp;
int num;
public:
TDatabase(int n):num(n)
{ rp = new T[num]; }
~TDatabase()
{ delete []rp; }
T &GetRecord(int recnum) throw (DBError);
};
template
T &TDatabase < T >::GetRecord(int recnum) throw (DBError)
{
if(0 <= recnum && recnum < num)
return rp[recnum];
else
throw DBError("Bad record number");
}
/* tdb.cpp */
#include
#include
#include "db.h"
using namespace std;
//Type of objects to store in database
class TRecord {
private:
string name;
public:
TRecord():name(){ }
TRecord(const string &s):name(s) { }
void Assign(const string &s) { name = s; }
const string & GetName()const { return name; }
};
int main()
{
int m; //Record number index
TDatabase *pdb; //Pointer to db of TRecords
pdb = new TDatabase(3); //create 3-record database
//Assign record data
pdb->GetRecord(0).Assign("George Washington");
pdb->GetRecord(1).Assign("John Adams");
pdb->GetRecord(2).Assign("Thomes JefferSon");
//Display database contents
for (m = 0; m <= 2; m++) {
cout << m << ": ";
cout << pdb->GetRecord(m).GetName() << endl;
}
//prompt user for record numbers
for (;;) {
cout << "Record number?(q to quit)";
cin >> m;
if ( !cin.good() ) break;
try {
TRecord &tr = pdb->GetRecord(m);
cout << m << ": " << tr.GetName() << endl;
}
catch (DBError error) {
cout << "* * * Error:" << error.what() << endl;
}
}
}
阅读(1207) | 评论(0) | 转发(2) |