gpt4 book ai didi

c++ - 添加析构函数后,在程序调用它之前出现错误

转载 作者:行者123 更新时间:2023-11-28 02:09:03 26 4
gpt4 key购买 nike

<分区>

(对不起我的英语,我是乌克兰人)我正在做一个实现“数字堆栈”(控制台应用程序)的程序。在删除 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;

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com