关于析构函数的调用问题:
xllfe 2002-04-23 02:27:23 书上说析构函数可以在下列两种情况被调用:
1。如果一个对象被定义在一个函数体内,则当这个函数结束时,则当这个函数结束时,该对象的析构函数就被自动调用
2。当一个对象使用new运算符被动态创建的,在使用delete运算符释放它时,delete将会自动调用析构函数。
一道例题:
#include <iostream.h>
#include "tdate1.h"
void main()
{
TDate1 today(1998,4,9),tomorrow(1998,4,10);
cout<<"todya is";
today.Print();
cout<<"tomorrow is";
tomorrow.Print();
}
class TDate1
{
public:
TDate1(int y,int m,int d);
~TDate1();
void Print();
private:
int year,month,day;
};
TDate1::TDate1(int y,int m,int d)
{
year=y;
month=m;
day=d;
cout<<"Constructor called.\n";
}
TDate1::~TDate1()
{
cout<<"Destructor called.\n";
}
void TDate1::Print()
{
cout<<year<<","<<month<<","<<day<<endl;
}
这道题调用析构函数应该属于自动调用析构函数的第一种情况,上机编译的时候出现了两次Destructor called.,即析构函数被调用了了两次,但怎么会被调用两次呢?因为对象是被定义在void main()这个函数内,这个函数只结束了一次呀!
出现了两次Constructor called.倒是可以理解,因为创建了两个对象,所以构造函数被调用了两次。
第二次调用析构函数是在什么时候?