由于其他人已经解释了这个问题的原因,这里有一个可能的解决方案来解决它。由于您似乎在编译时可能不知道数组大小,并且分配可能会限制使用std::vector<int>考虑使用指针实现。
#include <algorithm>
class Stack{
private:
    int cap;
    int* elements; // use a pointer
    int top;
public:
    Stack(){
        this->cap=5;
        this->top=-1;
        elements = new int[this->cap];
    }
    Stack(const Stack& s) 
         : cap(s.cap) , top(s.top), elements(NULL)
    {
         if(cap > 0) {
             elements = new int[cap];
         }
         std::copy(s.elements , s.elements + cap, elements );
    }
    Stack& operator=(Stack s) {
         swap(s, *this);
         return  *this;
    }
    ~Stack() {delete [] elements;}
    friend void swap(Stack& first, Stack& second)
    {
        using std::swap; 
        swap(first.top, second.top);
        swap(first.cap, second.cap);
        swap(first.elements, second.elements);
    }
};