(对不起我的英语,我和乌克兰语)我正在做一个实现了#"数字堆栈" (控制台应用程序)。我想要在删除stac之后添加将被清理的动态内存的析构函数。当我在没有析构函数的情况下执行stac时all right,如果我添加析构函数 - 我有error。应用程序结束时调用析构函数,但程序调用第一个函数时出错。没有析构函数我没有这个错误。这是我的源代码,析构函数被注释掉了。
#include<iostream>
#include<ctime>
using namespace std;
struct Oneof
{
int num;
Oneof* next;
};
class Stac
{
private:
Oneof * first;
public:
/*~Stac();*/
Stac();
Stac(Stac &n);
void New(int n); //Adding new element
int Remove(); //Reading last element and removing it
int SetLast(); //Reading last element without removing
void Read(); //Reading all stac
friend bool Eq(Stac a, Stac b); //Equive two another stacs
};
Stac::Stac(){first=NULL;}
Stac::Stac(Stac &n){first=n.first;}
/*Stac::~Stac()
{
while(first!=NULL)
{
Oneof *temp=first;
first=first->next;
delete temp;
}
}
*/
void Stac::New(int n) //Adding new element
{
Oneof* temp=new Oneof;
temp->num=n;
temp->next=first;
first=temp;
}
int Stac::Remove() //Reading last element and removing it
{
int a=first->num;
Oneof *temp=first;
first=first->next;
delete temp;
return a;
}
int Stac::SetLast() //Reading last element without removing
{
return first->num;
}
void Stac::Read() //Reading all stac
{
Oneof* temp=NULL;
Oneof* save=NULL;
save=first;
while(first!=NULL)
{
temp=first;
cout<<temp->num<<" ";
first=temp->next;
}
first=save;
}
bool Eq(Stac a, Stac b) //Equive two another stacs
{
Oneof* tempa=a.first;
Oneof* tempb=b.first;
while(tempa!=NULL && tempb!=NULL)
{
if(tempa->num==tempb->num)
{
tempa=tempa->next;
tempb=tempb->next;
}
else return false;
}
if(tempa==NULL && tempb==NULL)return true;
else return false;
}
int main()
{
Stac a;
srand(time(0));
for(int i=0; i<10; i++)
{
a.New(rand()%100);
}
Stac b(a);
cout<<"Chek equive...\n";
bool equ=Eq(a,b);
if(equ==0)cout<<"First!=Second\n";
else cout<<"First==Second\n";
cout<<"\nReading without removing first number of fisrt stac...\n";
int n=a.SetLast();
cout<<n<<endl;
cout<<"\nReading first Stac...\n";
b.Read();
cout<<"\n\nReading second Stac...\n";
a.Read();
cout<<"\n\nAdding new number and reading first Stac...\n";
b.New(rand());
b.Read();
cout<<"\n\nRemoving number and reading second Stac...\n";
int last=a.Remove();
cout<<last<<endl;
a.Read();
cout<<"\n\nChek equive...\n";
bool equ1=Eq(a,b);
if(equ1==0)cout<<"First!=Second\n\n";
else cout<<"First==Second\n\n";
system("pause");
return 0;
}
答案 0 :(得分:2)
您的函数 因此,Eq
按值<{em> 获取两个Stac
个对象
bool Eq(Stac a, Stac b)
a
和b
将是您输入的功能本地副本。因此,在函数结束后,它们将超出范围并且将调用它们的析构函数。要避免制作本地副本,请按const&
bool Eq(Stac const& a, Stac const& b)