朋友LinkedQueue <t>;预期宣言</t>

时间:2015-04-16 14:10:39

标签: c++

我是C ++的新手。我正在研究来自here的示例。我在行expected a declaration中收到friend LinkedQueue<T>;错误。我的理解是我需要使用像friend TYPE LinkedQueue<T>;这样的语句。网站上发布的代码是错误的吗?

使用链接表示实现队列的C ++程序

#include <iostream.h>
template<class T>
class Node
{
    friend LinkedQueue<T>;
    private:
    T data;
    Node<T> *link;
};
template<class T>
class LinkedQueue {
    public:
        LinkedQueue() {front = rear = 0;} // constructor
        ~LinkedQueue(); // destructor
        int IsEmpty() const
        {return ((front) ? 0 : 1);}
        T First() const; // return first element
        T Last() const; // return last element
        LinkedQueue<T>& Add(const T& x);
        LinkedQueue<T>& Delete(T& x);
    private:
        Node<T> *front;  // pointer to first node
        Node<T> *rear;   // pointer to last node
};

    template<class T>
LinkedQueue<T>::~LinkedQueue()
{// Queue destructor.  Delete all nodes.
    Node<T> *next;
    while (front) {
        next = front->link;
        delete front;
        front = next;
    }
}
template<class T>
T LinkedQueue<T>::First() const
{
    if (IsEmpty())   { cout<<"OutOfBounds()";  return -1; };
    return front->data;
}
template<class T>
T LinkedQueue<T>::Last() const
{
    if (IsEmpty()) { cout<<"OutOfBounds()";    return -1; };
    return rear->data;
}
    template<class T>
LinkedQueue<T>& LinkedQueue<T>::Add(const T& x)
{
    Node<T> *p = new Node<T>;
    p->data = x;
    p->link = 0;
    if (front) rear->link = p;  // queue not empty
    else front = p;             // queue empty
    rear = p;
    return *this;
}
    template<class T>
LinkedQueue<T>& LinkedQueue<T>::Delete(T& x)
{
    if (IsEmpty()) {  cout<<"OutOfBounds()"; return *this; };
    x = front->data;
    Node<T> *p = front;
    front = front->link;
    delete p;
    return *this;
}
void main(void)
{
    LinkedQueue<int> Q;
    int x;
    Q.Add(1).Add(2).Add(3).Add(4);
    cout << "No queue add failed" << endl;
    cout << "Queue is now 1234" << endl;
    Q.Delete(x);
    cout << "Deleted " << x << endl;
    cout << Q.First() << " is at front" << endl;
    cout << Q.Last() << " is at end" << endl;
    Q.Delete(x);
    cout << "Deleted " << x << endl;
    Q.Delete(x);
    cout << "Deleted " << x << endl;
    Q.Delete(x);
    cout << "Deleted " << x << endl;
    cout << "No queue delete failed " << endl;
}

感谢。

1 个答案:

答案 0 :(得分:3)

您必须在class LinkedQueue之前的某处声明class Node。 使用这样的前向声明:

template<class T>
class LinkedQueue; // forward declaration

template<class T>
class Node
{
    // definition ...    
};

template<class T>
class LinkedQueue {
    // definition ...
};