Getting the error "array bound is not an integer constant up to ']' token"

I try to implement a stack using an array, but I get an error.

class Stack{ private: int cap; int elements[this->cap]; // <--- Errors here int top; public: Stack(){ this->cap=5; this->top=-1; }; 

The specified line has the following errors:

 Multiple markers at this line - invalid use of 'this' at top level - array bound is not an integer constant before ']' token 

What am I doing wrong?

+4
source share
4 answers

In C ++, the size of the array must be a constant known at compile time. You will get an error if it is not.

Here you

 int elements[this->cap]; 

Note that this->cap not a constant known at compile time, since it depends on how big the cap .

If you want to have an array with a variable size, whose size is determined later, consider using std::vector , which can be changed at runtime.

Hope this helps!

+14
source

You cannot use this in a declaration like this. this is a constant pointer passed to non-stationary methods in your class. He does not exist outside this area.

Such array declarations need constant values ​​/ expressions for size. You do not want this, you need a container with a dynamic size. The solution is to use std::vector .

+2
source

Since others have already explained the cause of this problem, here is a possible solution to solve it. Since it seems you do not know the size of the array at compile time, and the purpose may limit the use of std::vector<int> consideration of the use of the pointer implementation.

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

Change

 int elements[this->cap]; 

to

 int* elements=new int[cap] 
0
source

Source: https://habr.com/ru/post/1479816/


All Articles