【发布时间】:2016-04-14 14:43:41
【问题描述】:
我正在尝试为我的 Stack 类(在 C++ 中)重载赋值运算符。当我运行我的输出时,我得到以下信息:
0 1 2 3 4 5 6 7 (空的) 释放内存! 释放内存!
第一行代表堆栈a,第二行代表堆栈b(见main())和“释放内存!”是析构函数。无论出于何种原因,堆栈 a 的内容都没有复制到堆栈 b 的内容中。我已经验证了容量空间是存在的(做了一堆打印语句),但没有发生复制。有人可以帮忙吗?
这是我的 Stack 构造函数、复制构造函数和析构函数:
/********************************/
Stack::Stack()
{
top = -1; // array counter starts at 0
stk = new int[MAXSIZE];
capacity = MAXSIZE;
}
/********************************/
/********copy constructor ***********/
Stack::Stack(const Stack& source) {
stk = new int[source.capacity]; // allocates new array space for the copy constructor
for (int i = 0; i <= top; i++) {
stk[i] = source.stk[i];
}
top = source.top;
capacity = source.capacity;
} /******* end copy constructor *******/
Stack::~Stack() {
cout << "Freeing memory!" << endl;
delete[] stk;
}
Here is my main:
int main() {
Stack a;
for (int i=0; i < 8; i++) {
a.push(i);
}
//cout << "\n Using copying incorrectly...\n";
//Stack b(a);
Stack b;
b = a;
a.display();
b.display();
【问题讨论】:
-
你是否重载了赋值运算符?如果可以,你能展示那部分吗?
标签: c++ stack overloading variable-assignment operator-keyword