嗨,我在将堆栈的简单弹出函数实现为数组程序时遇到了麻烦。代码如下,我不知道如何修复它。
我不确定所有可能的情况,所以如果你能告诉我,我将不胜感激!
#include "Exception.h"
template <typename Type>
class Drop_off_stack_as_array {
private:
int itop;
int ibottom;
int entry_count;
int array_capacity;
Type *array;
public:
Drop_off_stack_as_array( int = 10 );
Drop_off_stack_as_array( Drop_off_stack_as_array const & );
~Drop_off_stack_as_array();
int size() const;
bool empty() const;
Type top() const;
bool full() const;
void swap( Drop_off_stack_as_array & );
Drop_off_stack_as_array &operator = ( Drop_off_stack_as_array );
void push( Type const & );
Type pop();
void clear();
// Friends
template <typename T>
friend std::ostream &operator << ( std::ostream &, Drop_off_stack_as_array<T> const & );
};
template <typename Type>
Drop_off_stack_as_array<Type>::Drop_off_stack_as_array( int n ):
itop(0),
ibottom(0),
entry_count(0),
array_capacity(n),
array(new Type[array_capacity]){
//empty constructor
}
template <typename Type>
Drop_off_stack_as_array<Type>::Drop_off_stack_as_array( Drop_off_stack_as_array<Type> const &stack ):
itop( stack.itop ),
ibottom( stack.ibottom ),
entry_count( stack.entry_count ),
array_capacity( array_capacity ),
array( new Type[array_capacity] ) {
// The above initializations copy the values of the appropriate
// member variables and allocate memory for the data structure;
// however, you must still copy the stored objects.
for(int i = 0; i<array_capacity; i++){
array[i] = stack.array[i];
}
}
template <typename Type>
Drop_off_stack_as_array<Type>::~Drop_off_stack_as_array() {
delete[] array;
}
template <typename Type>
int Drop_off_stack_as_array<Type>::size() const {
return entry_count;
}
template <typename Type>
bool Drop_off_stack_as_array<Type>::full() const {
return (entry_count == array_capacity);
}
template <typename Type>
bool Drop_off_stack_as_array<Type>::empty() const {
return (entry_count == 0);
}
template <typename Type>
Type Drop_off_stack_as_array<Type>::top() const {
if(empty()){
throw underflow();
}
return array[itop];
}
template <typename Type>
void Drop_off_stack_as_array<Type>::swap( Drop_off_stack_as_array<Type> &stack ) {
std::swap( itop, stack.itop );
std::swap( ibottom, stack.ibottom );
std::swap( entry_count, stack.entry_count );
std::swap( array_capacity, stack.array_capacity );
std::swap( array, stack.array );
}
template <typename Type>
Drop_off_stack_as_array<Type> &Drop_off_stack_as_array<Type>::operator = ( Drop_off_stack_as_array<Type> rhs ) {
swap( rhs );
return *this;
}
template <typename Type>
void Drop_off_stack_as_array<Type>::push( Type const &obj ) {
if(full()){
array[ibottom] = 0;
itop = ibottom;
++ibottom;
}
else{
array[itop+1] = obj;
++itop;
++entry_count;
}
}
template <typename Type>
Type Drop_off_stack_as_array<Type>::pop() {
if(empty()){
throw underflow();
}
array[itop] = 0;
--itop;
--entry_count;
}
template <typename Type>
void Drop_off_stack_as_array<Type>::clear() {
delete [] array;
array = new Type(array_capacity);
}