[英]C++ array based stack implementation throwing errors
我是C ++的新手,所以這必須是微不足道的。 我使用數組實現了一個堆棧,但似乎無法從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,這樣您就不必編寫刪除myStack了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.