Getting error “array bound is not an integer constant before ']' token”

前端 未结 4 1848
暖寄归人
暖寄归人 2020-12-19 03:22

I am trying to implement a stack using an array but I receive an error.

class Stack{
private:
    int cap;
    int elements[this->cap]; // <--- Errors          


        
4条回答
  •  醉话见心
    2020-12-19 03:34

    Since other have already explained the cause of this issue, here is a possible solution to resolve it. Since it seems you may not know the array size at compile time and the assignment may restrict the use of std::vector consider using a pointer implementation.

    #include 
    
    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);
        }
    };
    

提交回复
热议问题