C++模版心得

       今天我终于抽出时间搞定了有生以来第一个自制的模版,功能很简单,就是实现一个栈的基本操作,取顶,压栈,弹栈。我发现模版这个东西其实挺好用的,我想以后我可以用这玩意儿实现很多STL中未提供的数据结构了,尽管估计做得效率会很低,但我只是为了玩。嘻嘻……

 

/* Stack.h
 * Writen by Sam Liang
 * At 30th Sept. 2006
 * A template which realize a stack. Just a test!
 */
const int MaxSize = 100;

template <class T>
class Stack
{
 public:
  // constructors
  Stack(int itsSize = MaxSize);
  Stack(const Stack &rhs);
  ~Stack() {delete [] pType;}

  // operators
  Stack& operator = (const Stack&);

  // member functions
  int GetSize() const {return itsSize;}
  T const TOP() ;
  void PUSH(T element);
  void POP() const
  {
   if(top != 0){
    top--;
   }
   else
    cout<<"ERROR: The stack is empty!"<<endl;
  };
 private:  
  T* pType;
  int itsSize;
  int top;
};

/*********************************************************
 * Main Constructor
 *********************************************************/
template <class T>
Stack<T>::Stack(int size):
itsSize(size)

 top = 0;
 pType = new T[size];
}

/*********************************************************
 * Copy Constructor
 *********************************************************/
template <class T>
Stack<T>::Stack(const Stack &rhs)
{
 itsSize = rhs.GetSize();
 pType = new T[itsSize];
 for(int i = 0; i<itsSize; i++)
  pType[i] = rhs[i];
}

/*********************************************************
 * operator =
 *********************************************************/
template <class T>
Stack<T>& Stack<T>::operator = (const Stack &rhs)
{
 if(this == &rhs)
  return *this;
 delete [] pType;
 itsSize = rhs.GetSize();
 pType = new T[itsSize];
 for(int i = 0; i<itsSize; i++)
  pType[i] = rhs[i];
 return *this;
}

/*********************************************************
 * Member Function -- TOP
 *********************************************************/
template <class T>
T const Stack<T>::TOP()
{
 if(top == 0)
 {
  cout<<"ERROR: Stack is null!"<<endl;
  return NULL;
 }
 return pType[top];
}

/*********************************************************
 * Member Function -- PUSH
 *********************************************************/
template <class T>
void Stack<T>::PUSH(T element)
{
 if(top<itsSize){
  top++;
  pType[top] = element;
 }
 else
  cout<<"ERROR: The stack is full!"<<endl;
}
/*********************************************************
 * Member Function -- POP
 *********************************************************/
/*template <class T>
void const Stack<T>::POP()
{
 if(top != 0){
  top--;
 }
 else
  cout<<"ERROR: The stack is empty!"<<endl;
}*/


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值