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: 在析构函数'Stack< T >::~Stack() [with T = int]': stackrunner.cc:9: 从这里实例化 stack.h:37: 错误: 不匹配调用'(LinkedQueue <int>)()'</p>

我是否错误地调用了析构函数?我不应该调用析构函数吗?调用类析构函数时是否会自动调用对象析构函数?

4

1 回答 1

4

Destructors are called automatically for you.

Calling a destructor on an already-destroyed-object is Undefined Behavior. It may crash, or lead to arbitrary results, or do real damage.

As a rule, never call a destructor explicitly (unless you have been using placement new to construct an object in existing storage).

于 2012-11-05T23:37:13.870 回答