这是我正在尝试使用的代码,它的编译但在 turbo c++ 中给出了意想不到的结果,但是程序在 dev C++ 中崩溃了,经过一些试验和错误,我发现关键字 delete 导致了问题,但是我我无法找出如何纠正错误。有人可以找出程序中的错误并向我解释。另外,有人可以告诉我如何使用智能指针编写相同的代码吗?
这是代码:
#include<iostream.h>
#include<process.h>
class list1
{
public:
virtual void getdata()
{ }
virtual ~list1()
{
cout<<endl<<"Destructor list1 called " ;
}
virtual void display()
{ }
};
class list2: public list1
{
public:
int data;
void getdata()
{
cout<<endl<<"Enter the data " ;
cin>>data ;
}
void display()
{
cout<<endl<<data ;
}
~list2()
{
cout<<endl<<"Destructor list2 called" ;
}
};
int main()
{
list1* ptr[3]; //array of pointers
char ch = 'y';
int n = 0;
while(ch=='y')
{
ptr[n] = new list2 ;
ptr[n]->getdata() ;
n++ ;
cout<<endl<<"Do you want to enter more of data " ;
cin>>ch ;
cout<<endl<<"The no of items currently added are: "<<n ;
}
ch='y';
while(ch=='y')
{
delete ptr[n];
n--;
cout<<endl<<"Item deleted " ;
cout<<endl<<"Do you want to delete more elements " ;
cin>>ch ;
cout<<endl<<"The no of items currently in the list are "<<n ;
}
int i = 0;
while(i < n)
{
ptr[i]->display() ;
i++ ;
}
cout<<endl ;
system("pause") ;
return 0;
}