2012-11-05 28 views
0

我正在實現一個使用兩個隊列作爲練習的堆棧。我在堆棧類的每個實例中都有兩個隊列對象。我想堆棧的析構函數調用隊列的析構函數。在線觀看時,似乎顯式使用析構函數並不常見,因爲它們往往會自動調用。我的代碼:我可以在另一個類的實例中顯式調用對象的析構函數嗎?

template<class T> 
class Stack { 
// LIFO objects 
    public: 
     Stack(int MaxStackSize = 10); 
     ~Stack(); 

     bool IsEmpty() const {return addS.IsEmpty();} 
     bool IsFull() const {return addS.getSize()==maxSize;} 

     Stack<T>& Add(const T& x); 
     Stack<T>& Delete(T& x); 
     void Print() const; 
    private: 
     LinkedQueue<T> addS; 
     LinkedQueue<T> delS; 
     int maxSize; 
}; 

template<class T> 
Stack<T>::Stack(int MaxStackSize) 
{ 
    maxSize = MaxStackSize; 
} 

template<class T> 
Stack<T>::~Stack() 
{ 
    ~addS(); 
    ~delS(); 
} 

template<class T> 
class LinkedQueue { 
// FIFO objects 
    public: 
     LinkedQueue() {front = rear = 0;} // constructor 
     ~LinkedQueue(); // destructor 
     bool IsEmpty() const 
      {return ((front) ? false : true);} 
     bool IsFull() const; 
     T First() const; // return first element 
     T Last() const; // return last element 
     LinkedQueue<T>& Add(const T& x); 
     LinkedQueue<T>& Delete(T& x); 
     void Print() const; // print the queue in order 
     int getSize() const; 

    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; 
     } 
} 

運行上面的代碼給我下面的錯誤:

stack.h: In destructor ‘Stack< T >::~Stack() [with T = int]’: stackrunner.cc:9: instantiated from here stack.h:37: error: no match for call to ‘(LinkedQueue< int >)()’

我是否正確調用析構函數?我應該不是在調用析構函數嗎?當類析構函數被調用時,對象destrcutors是否自動調用?

+0

將會爲您調用析構函數。 – chris

回答

4

自動爲您調用析構函數。

在已經銷燬的對象上調用析構函數是Undefined Behavior。它可能會崩潰,或導致任意結果,或造成實際損害。

通常,絕不會顯式調用析構函數(除非您已經使用placement new來在現有存儲中構造對象)。

+0

在類的析構函數中調用類對象的析構函數嗎? –

+0

是的。 。 。 。 。 。 –

相關問題