#include <iostream> using namespace std; class MyQueue { public: MyQueue(int QueueCapacity); virtual ~MyQueue(); void ClearQueue(); bool QueueEmpty()const; int QueueLengh()const; bool Queuefull()const; bool EnQueue(int element); bool DeQueue(int &element); void QueueTraverse(); private: int* m_pQueue; int m_iQueuelen; int m_iQueueCapacity; int m_iHead; int m_iTail; }; MyQueue::MyQueue(int QueueCapacity) { m_iQueueCapacity = QueueCapacity; m_iHead = 0; m_iTail = 0; m_iQueuelen = 0; m_pQueue= new int(QueueCapacity); } MyQueue::~MyQueue() { delete m_pQueue; m_pQueue = NULL; } void MyQueue::ClearQueue() { m_iHead = 0; m_iTail = 0; m_iQueuelen = 0; } bool MyQueue::QueueEmpty()const { return (m_iQueuelen == 0) ? true : false; } int MyQueue::QueueLengh()const { return m_iQueuelen; } bool MyQueue::Queuefull()const { return (m_iQueueCapacity == m_iQueuelen) ? true : false; } bool MyQueue::EnQueue(int element) { if (Queuefull()) { return false; } else { m_pQueue[m_iTail] = element; m_iQueuelen++; m_iTail++; m_iTail = m_iTail % m_iQueueCapacity; return true; } } bool MyQueue::DeQueue(int &element) { if (QueueEmpty()) { return false; } else { element = m_pQueue[m_iHead]; m_iQueuelen--; m_iHead++; m_iHead = m_iHead % m_iQueueCapacity; return true; } } void MyQueue::QueueTraverse() { for (int i = m_iHead; i < m_iQueuelen + m_iHead; i++) { i = i % m_iQueueCapacity; cout << m_pQueue[i] << endl; } } int main(void) { MyQueue *Safe = new MyQueue(4); Safe->EnQueue(4); Safe->EnQueue(5); //Safe->EnQueue(6); //执行这句就会奔溃 Safe->QueueTraverse(); system("pause"); return 0; }
申请内存时错误的使用了(),应使用[];
恕我直言,你这个所谓的“环形队列”完全就是四不像,建议看看相关代码再自己实践。