jeudi 26 février 2015

C++ array based stack implementation throwing errors


I'm kinda new to C++, so this must be something trivial. I've implemented a stack using an array but can't seem to call from main. Here's my main( ).



#include <iostream>
#include <cstdlib>
#include "stack.cpp"

int main(){

myStack = new Stack(10);
return 0;
}


Here's my .hpp



#include <string>

class Stack {

public:
Stack(int capacity);

void push(int value);

int peek();
void pop();
bool isEmpty();

~Stack() {
delete[] storage;
}

private:
int top;
int capacity;
int *storage;
};


And here's my .cpp



#include "stack.hpp"


Stack::Stack(int capacity) {
if (capacity <= 0)
throw std::string("Stack's capacity must be positive");
storage = new int[capacity];
this->capacity = capacity;
top = -1;
}

void Stack::push(int value) {
if (top == capacity)
throw std::string("Stack's underlying storage is overflow");
top++;
storage[top] = value;
}

int Stack::peek() {
if (top == -1)
throw std::string("Stack is empty");
return storage[top];
}

void Stack::pop() {
if (top == -1)
throw std::string("Stack is empty");
top--;
}

bool Stack::isEmpty() {
return (top == -1);
}


This is the error message.



client.cpp: In function ‘int main()’:
client.cpp:7:3: error: ‘myStack’ was not declared in this scope
myStack = new Stack(10);
^


Wonder what am I missing.




Aucun commentaire:

Enregistrer un commentaire