【发布时间】:2014-02-14 00:26:34
【问题描述】:
下面我将显示我的程序运行时的输出:
现在我将显示预期的输出:
我将展示我教授的代码正在实现的函数,或者更确切地说是我在下面制作的“复制构造函数”或重载函数:
void operator=(const Stack& s)
{
if (s.top == NULL){
num_items = 0;
top = NULL;}
else
{
top = new Node;
top->data = s.top->data;
Node* newP = top;
num_items = 1;
for(Node* curr = s.top->link; curr != NULL; curr = curr->link)
{
if(num_items != MAX_SIZE)
{
newP->link = new Node;
newP = newP->link;
newP->data = curr->data;
++num_items;
}
}
}
}
最后我会展示使用这个函数的代码,我的导师的代码:
Stack<int> s3;
s3 = s3 + s2;
cout << "*declare s3 as a copy of s2 (stack s3 = s2)\ns3=" << s3 << endl; // copy constructor (=)
cout << "s3.Size()=" << s3.Size() << endl;
cout << "s3.IsEmpty()=" << ((s3.IsEmpty()) ? "T" : "F") << endl;
cout << "s3.IsFull()=" << ((s3.IsFull()) ? "T" : "F") << endl;
cout << "s3.Peek()=" << s3.Peek() << endl;
cout << endl;
我尝试了各种方法,例如制作一个机器人指针来尝试确定堆栈底部的位置,然后像这样打印出来,但它似乎没有用,或者我写错了。
根据要求,这是 operator+ 代码:
Stack operator+(const Stack& s) const
{
// copy the first list
Stack t = *this;
Stack u = *this;
Node *n = s.top;
// iterate through the second list and copy each element to the new list
while (n != NULL && !t.IsFull())
{
t.Push(n->data);
u.Push(n->data);
n = n->link;
}
return u;
}
【问题讨论】:
-
s3应该是s2的副本?那你为什么要s3 = s3 + s2? -
@remyabel 我的导师写了这个的主要功能,所以老实说我不确定,但我不允许更改他的代码中的任何内容
-
在这种情况下,显示
operator+。 -
@remyabel 我已经对其进行了编辑以显示该功能
-
@remyabel ideone.com/o3n1fG
标签: c++ linked-list stack