c++ exception application

class QueueException : public exception
{
public:
 QueueException(const char* strMsg){m_strMsg = strMsg;};
 virtual const char* what() const{return m_strMsg;};
private:
 const char* m_strMsg;
};

template<class T>
class Queue
{
public:
 Queue(int nMaxSize){
  m_nMaxSize = nMaxSize+1;
  m_data = new T[nMaxSize+1];
  m_nHead = 0;
  m_nTail = 0;
 };
 T Pop() throw(QueueException){
  if(m_nHead == m_nTail)//empty
   throw QueueException("Queue is empty when popping");
  return m_data[m_nHead++];
 };
 void Push(const T& t) throw(QueueException){
  if((m_nTail+1)%m_nMaxSize == m_nHead)//full
   throw QueueException("Queue is full when pushing");
  m_data[m_nTail++] = t;
 }
 size_t Capacity(){
  return (m_nTail+m_nMaxSize-m_nHead)%m_nMaxSize;
 }
private:
 int m_nHead;
 int m_nTail;
 int m_nMaxSize;
 T* m_data;
};

int main()
{
 Queue<int> q(5);
 try{
  q.Push(23);
  q.Push(34);
  cout<<q.Pop()<<endl;
  cout<<q.Pop()<<endl;
  q.Pop();
 }
 catch (QueueException e) {
  cout<<e.what();
 }
 return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章