c++ 队列基本操作实现

纯练手~

使用c++模板实现队列,测试文件在codeblocks下编译通过,在引用头文件时,需要#include "StaticQueue.cpp"不然会报错,明天再寻求原因吧。

头文件:

#ifndef STATICQUEUE_H_INCLUDED
#define STATICQUEUE_H_INCLUDED

template
class StaticQueue
{
public:

    StaticQueue();
    StaticQueue(int size);
    ~StaticQueue();
    void enqueue(T data);
    T dequeue();
    bool isEmpty();
    bool isFull();
    int count();
    void display();

private:

    int rear;
    int front;
    int size;
    const static int DEFAULT;
    T* queue;

};

#endif // STATICQUEUE_H_INCLUDED

实现文件:

#include 
#include 
#include "StaticQueue.h"

using namespace std;
const int DEFAULT = 10;

template
StaticQueue::StaticQueue()
{
    queue = new T[DEFAULT];
    size = DEFAULT;
    rear = front = 0;
}

template
StaticQueue::StaticQueue(int size)
{
    queue = new T[size];
    this->size = size;
    rear = front = 0;
}

template
StaticQueue::~StaticQueue()
{
    delete [] queue;
    queue = 0;
    size = 0;
    rear = front = 0;
}

template
bool StaticQueue::isEmpty()
{
    if(front == rear)
        return true;
    return false;
}

template
bool StaticQueue::isFull()
{
    if((rear - front) >= size)
        return true;
    return false;
}

template
void StaticQueue::enqueue(T data)
{
    if(isFull() == 0)
    {
        queue[rear] = data;
        rear++;
    }
    else
        fprintf(stderr, "Queue is full now.\n");
}

template
T StaticQueue::dequeue()
{
    if(isEmpty() == 0)
    {
        T tmp = queue[front];
        front++;
        return tmp;
    }
    else
    {
        fprintf(stderr, "Queue is empty now.\n");
        return NULL;
    }
}

template
int StaticQueue::count()
{
    return(rear-front);
}

template
void StaticQueue::display()
{
    int i;
    for(i=front; i

测试文件:

//#include "StaticQueue.cpp"
#include 
#include 
#include "StaticQueue.cpp"
using namespace std;

int main()
{
    StaticQueue q(4);
    cout<


你可能感兴趣的:(c++ 队列基本操作实现)