将相同大小的两个堆栈的值相加

Adding values of two stacks of the same size

本文关键字:两个 堆栈      更新时间:2024-05-10

我只是在练习创建一个堆栈类,并试图重载operator=operator+。到目前为止,我已经成功地使operator=过载。

假设我的目标是能够在主中执行st3 = st1 + st2;操作,其中st1、st2、st3是类堆栈的对象,并且假设它们都具有相同的大小并且都是int值。

现在st3没有返回任何值。

在我的课堂上,我有:

stack& operator+(stack& otherStack){
int sum = 0;
stack res;
while ((!this->isEmpty()) && (!otherStack.isEmpty())) {
sum = this->top() + otherStack.top();
res.push(sum);
this->pop();
otherStack.pop();
}
return res;
}

这是我使用递归的print()函数,它也在class stack中。它只打印st1和st2很好的

void printStack(){
if (isEmpty())
return;
int x = this->top();
this->pop();
this->printStack();
this->push(x);
}
stack& operator+(stack& otherStack){
stack res;
...
return res;
}

res是一个自动变量。当它超出范围时,它的寿命就结束了;即当函数返回时。返回一个对该对象的引用,该对象的生存期已结束。返回的引用总是挂起的,尝试访问对象将导致未定义的行为。

解决方案:返回一个对象;而不是引用。

修改操作数的

Operator+是非常规的,我强烈建议不要这样设计。