c++ - error: invalid use of non-static data member 'capacity' int data[capacity]; -


i don't understand why data variable in private causing me problems. thought might able fix problem declaring variables first time in constructor, feel there must way define variables privately , set them in constructor without problems. how fix this? mean invalid use of non-static data memory?

#include <cassert> #include <iostream> #include <vector> using namespace std;  class stack{ private:      int capacity;     int data[capacity];     int top;     int bottom;   public:    stack(){         top=0;         bottom=0;         capacity=100;    }     bool isempty(){         return top==bottom;    }     int pop(stack s){         //assert(!isempty());         int elem = data[top];         top--;         return elem;      }     void push(stack s,int x){         assert(top<capacity-1);         top++;         data[top]=x;         return;    }  };  int main() {     return 0;     } 

variable-length arrays not allowed in standard c++. use either dynamic array, or better, std::vector<int> data(capacity).

also, should initialize member variables using constructor initializer list,

stack(): capacity(100), data(capacity), top(0), bottom(0){} // assuming use `std::vector<int> data;` 

if cannot use std::vector (homework, otherwise should!), can use dynamic array

int* data; 

and declare constructor as

stack(): capacity(100), data(new int[capacity]), top(0), bottom(0){} 

then, have declare destructor

~stack() { delete[] data;}  

so don't have memory leaks. next should define copy constructor , assignment operator, things become bit complicated. use std::vector<int> if can.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -