2013-02-25 148 views
1

--------------------- Queue.h ------------ --------C++:[class]未在此範圍內聲明

#ifndef QUEUE_H 
#define QUEUE_H 

#include <iostream> 
#include "MyException.h" 

using namespace std; 

template<class T> 
class Queue; 

template<class T> 
ostream& operator<<(ostream&,Queue<T>&); 

template<class T> 
class Queue 
{ 
    public: 
     friend ostream& operator<< <T>(ostream&,Queue<T>&); 
     Queue(); 
     Queue(const Queue<T>& other); 
     Queue<T>& operator=(const Queue<T>& other); 
     ~Queue(); 
    void enqueue(const T& el); 
     T dequeue(); 
     void increasePriority(const T& el); 
     bool isEmpty(); 

    private: 
     class Node 
     { 
      public: 
       Node(const T& data, Node* n = 0) 
       { 
        element = data; 
        next = n; 
       } 

       T element; 
       Node* next; 
     }; 
     Node* head; 

}; 

#include "Queue.C" 

#endif 

我們不允許更改.h(above)文件。

--------------------- Queue.C --------------------

#include "Queue.h" 

    template<class T> 
    ostream& operator << (ostream &strm, Queue<T> &obj) 
    { 
     if (obj.isEmpty()) 
     { 
      strm << "[]"; 
      return strm; 
     } 
     else 
     { 
      strm << '['; 
//line 28 
    Node* tmp = new Node(); 
      tmp = obj.head; 
      strm << tmp.element + ','; 
      while (tmp->next != 0) 
      { 
       tmp = tmp->next; 
       if (tmp-next != 0) 
       { 
        strm << tmp.element + ','; 
       } 
       else 
       { 
        strm << tmp.element; 
       } 
      } 
      strm << ']'; 
      delete [] tmp; 
      tmp = 0; 
      return strm; 
     } 
     return strm; 
    } 
    //...more code 
    Queue::Queue() 
    { 
//line 54 
    head = new Node(); 
     } 

於是從一些代碼我收到錯誤如下:

Queue.C: In function ‘std::ostream& operator<<(std::ostream&, Queue<T>&)’: 
Queue.C:28: error: ‘Node’ was not declared in this scope 
Queue.C:28: error: ‘tmp’ was not declared in this scope 
Queue.C:28: error: expected type-specifier before ‘Node’ 
Queue.C:28: error: expected ‘;’ before ‘Node’ 
Queue.C:34: error: ‘next’ was not declared in this scope 
Queue.C: At global scope: 

Queue.C:54: error: ‘head’ was not declared in this scope 
Queue.C:54: error: expected type-specifier before ‘Node’ 
Queue.C:54: error: expected ‘;’ before ‘Node’ 
+1

'Node'是'Queue'的一部分。 – chris 2013-02-25 06:49:51

+0

由於源文件包含在頭文件中,因此不需要將頭文件包含在源文件中。 – 2013-02-25 06:52:17

回答

1

要包括在Queue.CQueue.h,反之亦然。您不應該在Queue.C中包含Queue.h,因爲您希望可以通過標題訪問整個實施。

接下來,Node聲明中Queue,所以在執行它與Queue類模板的範圍前綴:

Queue<T>::Node ...; // instead of Node 
1

您必須前綴Node它是在限定的範圍,即Queue

Queue<T>::Node* tmp = new Queue<T>::Node(); 

,否則編譯器不知道你是哪個Node型。

但在下一行中,您將用obj.head覆蓋您的tmp指針並丟失新創建的Node。這將導致內存泄漏。在任何情況下,您都不需要在運算符中創建新的Node,該運算符只輸出隊列。

再往下,你

delete [] tmp; 

其刪除隊列中的最後一個元素。我想,你不應該在這個輸出操作符中以任何方式修改Queue。

這會導致下一個點,該運營商應聲明

friend ostream& operator<< <T>(ostream&, const Queue<T>&); 

,以避免意外修改Queue對象。