我基本上试图通过将其传递给函数来反转堆栈。但是,当我运行程序时程序崩溃,我找不到逻辑错误,因为我甚至重载了赋值运算符来处理指针数据成员。
#include <iostream>
using namespace std;
/***************************************************************************/
class AStack {
public:
AStack();
AStack(int);
~AStack();
AStack operator = (AStack s);
void push(int);
int pop();
int top();
bool isEmpty();
void flush();
private:
int capacity;
int* a;
int index = -1; // Index of the top most element
};
AStack::AStack() {
a = new int[25];
capacity = 25;
}
AStack::AStack(int size) {
a = new int[size];
capacity = size;
}
AStack::~AStack() {
delete[] a;
}
AStack AStack::operator = (AStack s) {
capacity = s.capacity;
int* a = new int[capacity];
for (int i = 0; i < capacity; i++) {
a[i] = s.a[i];
}
index = s.index;
return *this;
}
void AStack::push(int x) {
if (index == capacity - 1) {
cout << "\n\nThe stack is full. Couldn't insert " << x << "\n\n";
return;
}
a[++index] = x;
}
int AStack::pop() {
if (index == -1) {
cout << "\n\nNo elements to pop\n\n";
return -1;
}
return a[index--];
}
int AStack::top() {
if (index == -1) {
cout << "\n\nNo elements in the Stack\n\n";
return -1;
}
return a[index];
}
bool AStack::isEmpty() {
return (index == -1);
}
void AStack::flush() {
if (index == -1) {
cout << "\n\nNo elements in the Stack to flush\n\n";
return;
}
cout << "\n\nFlushing the Stack: ";
while (index != -1) {
cout << a[index--] << " ";
}
cout << endl << endl;
}
/***************************************************************************/
void reverseStack(AStack& s1) {
AStack s2;
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
s1 = s2;
}
/***************************************************************************/
int main() {
AStack s1;
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
reverseStack(s1);
cout << "\n\nFlushing s1:\n";
s1.flush();
system("pause");
return 0;
}
答案 0 :(得分:1)
您没有提供复制构造函数,并且赋值运算符按值获取参数。语句s1 = s2
通过调用隐式定义的复制构造函数来创建s2
的副本,该复制构造函数复制指针,然后分配给s1
。在表达式的末尾,副本被销毁,在指针上调用delete []
。在函数结束时,s2
的析构函数运行并再次尝试delete []
相同的指针。
你需要提供一个能做正确事情的复制构造函数。