基于 C++ 数组的堆栈实现抛出错误

C++ array based stack implementation throwing errors

我对 C++ 有点陌生,所以这一定很简单。我已经使用数组实现了一个堆栈,但似乎无法从 main 调用。 这是我的 main( ).

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

int main(){

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

这是我的 .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;
};

这是我的 .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);
}

这是错误信息。

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

想知道我错过了什么。

Stack* myStack = new Stack(10);
...
delete myStack;

或者在堆栈上声明 myStack

Stack myStack(10);

另请查看 std::unqiue_ptr,这样您就不必编写 delete myStack。