简体   繁体   English

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

[英]C++ array based stack implementation throwing errors

I'm kinda new to C++, so this must be something trivial. 我是C ++的新手,所以这必须是微不足道的。 I've implemented a stack using an array but can't seem to call from main. 我使用数组实现了一个堆栈,但似乎无法从main调用。 Here's my main( ). 这是我的主要()。

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

int main(){

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

Here's my .hpp 这是我的.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 这是我的.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. 不知道我错过了什么。

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

Alternatively declare myStack on the stack 或者在堆栈上声明myStack

Stack myStack(10);

Also look into std::unqiue_ptr so you don't have to write delete myStack. 另请查看std :: unqiue_ptr,这样您就不必编写删除myStack了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM