0

我不是程序员,实际上是一名律师,在过去一年左右的时间里学习了 C++。我这样做是一种爱好。无论如何,我已经开始尝试使用模板,只是不知道该怎么做。我正在使用节点结构实现模板化队列,我还在 Queue 类之外对其进行模板化和声明。如何将 Queue 的模板化类型传递给 Node 结构?任何其他意见一般表示赞赏。谢谢你。示例代码:

template<class T> struct Node{
Node<T> *next;  T data;
Node<T> * previous;
Node (T d) {data = d;}
};


template<class Q> class Queue
{
    int count;
    Node<Q>  *head;  -> doesn't work -'Node<T>::data uses undefined class Q.  
    Node<Q> *tail;     


public:
    Queue() : count(0), head(NULL), tail(NULL) {}
    ~Queue();


    void Enqueue(Q data);
    Node<Q>* Dequeue();
    std::ostream& Print(std::ostream& os) const;
};

void Queue<class Q>::Enqueue(Q data)
{
    Node<Q> * newNode = new Node<Q>(data);
    if(!head)
        head = tail = newNode;
    else
    {
        tail->next = newNode;
        tail = newNode;
        tail->next=NULL;
    }
    ++count;
}

Queue<class Q>::~Queue()
{
        while(head)
        {
            Node<Q> * tmp = head;
            head=head->next;
            delete tmp;
        }
}


Node<Q> * Queue<class Q>::Dequeue()
{
    if(!head) return NULL;

    Node<Q> * temp = head;
    head = head->next;
    --count;
    return temp;
}

std::ostream& Queue<class Q>::Print(std::ostream& os) const
{
    if(!head)
    {
        os<<"Empty list"<<endl;
        return os;
    }

    for(Node<Q> *itr = head; itr!=NULL; itr=itr->next)
        os<<" "<<itr->data <<" "<<endl;

    return os;
}


std::ostream& operator<<(std::ostream& os, const Queue<Q>& q)
{
   return q.Print(os);
}
4

1 回答 1

1
template<typename T> struct Node{
Node<T> *next;  T data;
Node<T> * previous;
Node (T d) {data = d;}
};


template<typename Q> class Queue
{
    int count;
    Node<Q>  *head;
    Node<Q> *tail;     


public:
    Queue() : count(0), head(NULL), tail(NULL) {}
    ~Queue();


    void Enqueue(Q data);
    Node<Q>* Dequeue();
    std::ostream& Print(std::ostream& os) const;
};

template<typename Q>
void Queue<Q>::Enqueue(Q data)
{
    Node<Q> * newNode = new Node<Q>(data);
    if(!head)
        head = tail = newNode;
    else
    {
        tail->next = newNode;
        tail = newNode;
        tail->next=NULL;
    }
    ++count;
}

template<typename Q>
Queue<Q>::~Queue()
{
        while(head)
        {
            Node<Q> * tmp = head;
            head=head->next;
            delete tmp;
        }
}

template<typename Q>
Node<Q> * Queue<Q>::Dequeue()
{
    if(!head) return NULL;

    Node<Q> * temp = head;
    head = head->next;
    --count;
    return temp;
}

template<typename Q>
std::ostream& Queue<Q>::Print(std::ostream& os) const
{
    if(!head)
    {
        os<<"Empty list"<<endl;
        return os;
    }

    for(Node<Q> *itr = head; itr!=NULL; itr=itr->next)
        os<<" "<<itr->data <<" "<<endl;

    return os;
}

template<typename Q>
std::ostream& operator<<(std::ostream& os, const Queue<Q>& q)
{
   return q.Print(os);
}

我为您修复了编译错误。

于 2013-05-24T03:39:41.823 回答