#pragma once #include #include "stack.h" template class arrayStack : public Stack { private: T* stack; int stackTop; int length; public: arrayStack(int initialCapacity = 10); virtual ~arrayStack() { delete[] stack; } virtual bool empty() const override { return stackTop == -1; } virtual int size() const override { return stackTop + 1; } virtual T& top() override; virtual void pop() override; virtual void push(const T& theElement) override; virtual void show() const; arrayStack& operator=(const arrayStack& x); arrayStack(const arrayStack& x); }; template arrayStack::arrayStack(int initialCapacity) { length = initialCapacity; if(length < 0) { throw std::invalid_argument("Initial Error: Length < 0"); length = 1; } stack = new T[length]; stackTop = -1; } template T& arrayStack::top() { if (stackTop == -1) throw std::invalid_argument("Top Error: No Element in Stack"); return stack[stackTop]; } template void arrayStack::pop() { if (stackTop == -1) throw std::invalid_argument("Pop Error: Empty Stack"); if constexpr (!std::is_trivially_destructible::value) { stack[stackTop].~T(); // 只有在 T 有析构函数时才调用 } stackTop--; } template void arrayStack::push(const T& theElement) { if(stackTop == length - 1){ T* tmp = new T[length * 2]; for(int i = 0; i < length; i++){ tmp[i] = stack[i]; } delete[] stack; stack = tmp; length *= 2; } stackTop++; stack[stackTop] = theElement; } template arrayStack::arrayStack(const arrayStack& x) { length = x.length; stackTop = x.stackTop; stack = new T[length]; for (int i = 0; i <= stackTop; ++i) { stack[i] = x.stack[i]; } } template arrayStack& arrayStack::operator=(const arrayStack& x) { if (this != &x) { delete[] stack; length = x.length; stackTop = x.stackTop; stack = new T[length]; for (int i = 0; i <= stackTop; ++i) { stack[i] = x.stack[i]; } } return *this; } template void arrayStack::show() const { for (int i = 0; i <= stackTop; i++) { std::cout << stack[i] << " "; } std::cout << std::endl; }