模板类 基础

export关键字
可以让模板的 成员申明和定义分开两个文件
但是要加 
ep:
//头文件申明加export关键字,定义就可以放另外一个文件中按常用方法定义
export template <class T>
class Stack
{
  …
};
 

////////////////////////////////////////////////////////
////////////////stacktp.h///////////////////////////////
#ifndef STACK_H_
#define STACK_H_
template <class Type>
class Stack
{
private:
 enum {max=10};
 Type items[max];
 int top;
public:
 Stack();
 bool isempty ();
 bool isfull ();
 bool push(const Type & item);
 bool pop(Type & item);
};

template <class Type>
Stack<Type>::Stack()
{
 top=0;
}

template <class Type>
bool Stack<Type>::isempty()
{
 return 0==top;
}

template <class Type>
bool Stack<Type>::isfull()
{
 return max==top;
}

template <class Type>
bool Stack<Type>::push(const Type & item)
{
    if (top<max)
 {
  items[top++]=item;
  return true;
 }
 else
  return false;
}

template <class Type>
bool Stack<Type>::pop(Type & item)
{
 if (top>0)
 {
  item=items[--top];
  return true;
 }
 else
  return false;
}

#endif

 

/////////////////////////////////////////////////////
///////////main.cpp//////////////////////////////////
#include <iostream>
#include <string>
#include <cctype>
#include "stacktp.h"
using std::cin;
using std::cout;

int main(void)
{
    Stack<std::string> st;
 char ch;
 std::string po;
 cout<<"please enter a to add a purchase order, \n"
  <<"p to process a po,or Q to quit.\n";
 while (cin>>ch && toupper(ch)!='Q')
 {
  while (cin.get()!='\n')
   continue;
  if (!isalpha(ch))
  {
   cout<<'\a';
   continue;
  }
  switch (ch)
  {
  case 'A':
  case 'a':cout<<"enter a po number to add: ";
   cin>>po;
   if (st.isfull())
    cout<<"stack is full\n";
   else
    st.push(po);
   break;
  case 'P':
  case 'p': if (st.isempty())
       cout<<"stack is empty\n";
         else
      {
       st.pop(po);
       cout<<"po# "<<po<<"poped.\n";
       break;
      }
  
  }
  cout<<"please enter a to add a purchase order, \n"
  <<"p to process a po,or Q to quit.\n";
  } 
 return 0;
}

posted @ 2007-03-05 10:59  Edward Xie  阅读(160)  评论(0)    收藏  举报