我正在实现一个使用两个队列作为练习的堆栈。我在堆栈类的每个实例中都有两个队列对象。我想堆栈的析构函数调用队列的析构函数。在线观看时,似乎显式使用析构函数并不常见,因为它们往往会自动调用。我的代码:我可以在另一个类的实例中显式调用对象的析构函数吗?
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是否自动调用?
将会为您调用析构函数。 – chris