E2.
What is wrong with the following attempt to use the copy constructor to implement the overloaded assignment operator for a linked Stack?
void Stack::operator=(const Stack&original)
{
Stack new_copy(original);
top_node=new_copy.top_node;
}
How can we modify this code to give a correct implementation?
正解:
void Stack::operator=(const Stack&original)
{
Node*new_top,*new_copy,*original_node=original.top_node;
if(original_node==NULL)
new_top=NULL;
else
{
new_copy=new_top=new Node(origanal_node->entry);
while(original_code->NULL)
{
original_node=original_node->next;
new_copy->next=new Node(original_node->entry);
cew_copy=new_copy->next;
}
}
while(!empty())
pop();
top_node=new_top;
}