一 析构函数
#include<iostream>
using namespace std;
class student
{
public:
char* m_name;
float m_score;
public:
student();
~student();
};
student::student()
{
int i=0;
m_name =new char[10];
for(i;i<5;i++)
{
m_name[i]=i+'a'; //从 a到e
}
m_name[i]='\0';
}
student::~student()
{
}
int main()
{
student *pstu=new student;
cout<<pstu->m_name<<endl;
char*str=pstu->m_name;
delete(pstu);
cout<<str<<endl;
system("pause");
return 0;
}
此时,str是可以输出的,但是指向m-name的对象pstu已经被删除了,若程序结束m-name也不会回收,如下图
这时候就需要析构函数回收
student::~student()
{
if(m_name!=NULL)
{
delete[]m_name;
}
}
二 析构函数执行时机
#include<iostream>
using namespace std;
class AA
{
public:
AA()
{
cout<<"AA"<<endl;
}
~AA()
{
cout<<"~AA"<<endl;
}
};
int main()
{
//AA 只显示AA 都执行 析构在reurn 0后执行
{
// AA a; 都执行 会显示AA~AA
/*AA *p=new AA;
delete(p); new 构造 delete 析构 */
// AA*a=(AA*)malloc(sizeof(AA)); free(a) 不执行构造析构
}
system("pause");
return 0;
}
三 小练习 万年历
#include<iostream>
using namespace std;
class Date
{
private:
int m_year;
int m_month;
int m_day;
public:
Date();
void setyear(int year);
void seymonth(int month);
void setday(int day);
void show();
void reback(int year,int month,int day);
};
Date::Date()
{
m_year=1900;
m_month=1;
m_day=1;
}
void Date::setyear(int year)
{
m_year=year;
}
void Date::seymonth(int month)
{
if(month>=1&&month<=12)
m_month=month;
}
void Date::setday(int day)
{
if(day>=1&&day<=30)
m_day=day;
}
void Date::show()
{
cout<<m_year<<"-"<<m_month<<"-"<<m_day<<endl;
}
void Date::reback(int year,int month,int day)
{
m_year=year;
m_month=month;
m_day=day;
}
int main()
{
Date aaa;
aaa.show();
aaa.setday(3);
aaa.reback(2001,10,16);
aaa.show();
system("pause");
return 0;
}
四 对象的种类
全局对象 临时对象 局部对象
#include<iostream>
using namespace std;
class AA
{
public:
AA()
{
cout<<"AA"<<endl;
}
~AA()
{
cout<<"~AA"<<endl;
}
};
AA a;
//全局对象
int main()
{
AA();//临时对象 生命周期 这一行
AA b;//局部对象
system("pause");
return 0;
}
五 实现一个队列
#include<iostream>
using namespace std;
class queue
{
struct Node
{
int id;
Node*pNext;
};
private:
Node *m_pHead;
Node *m_pEnd;
int m_nsize;
public:
queue();
~queue();
public:
void push(int id);
int pop();
void print();
};
void queue::push(int id)
{
Node *ptemp=new Node;
ptemp->id=id;
ptemp->pNext=NULL;
if(m_pHead==NULL)
{
m_pHead=ptemp;
}
else
{
m_pEnd->pNext=ptemp;
}
m_pEnd=ptemp;
m_nsize++;
}
int queue::pop()
{
int id=-1;
Node*Del=NULL;
if(m_pHead!=NULL)
{
Del=m_pHead;
m_pHead=m_pHead->pNext;
id=Del->id;
delete Del;
Del=NULL;
m_nsize--;
}
return id;
}
queue::queue()
{
m_pHead=NULL;
m_pEnd=NULL;
m_nsize=0;
}
queue::~queue()
{
Node*pmark=NULL;
while(m_pHead!=NULL)
{
pmark=m_pHead;
m_pHead=m_pHead->pNext;
delete pmark;
pmark=NULL;
}
}
void queue::print()
{
Node*prin=m_pHead;
while(prin!=NULL)
{
cout<<prin->id;
prin=prin->pNext;
}
cout<<" size:"<<m_nsize<<endl;
}
int main()
{
queue qq;
qq.push(1);
qq.push(2);
qq.push(3);
qq.push(4);
qq.push(5);
qq.push(6);
int n=qq.pop();
qq.print();
cout<<n<<endl;
system("pause");
return 0;
}