默认的析构函数
我们迄今使用过的所有对象都是被类的默认析构函数自动销毁的。如果我们不自行定义析构函数,编译器就总是生成默认的析构函数。默认的析构函数不能删除new运算符在自由存储器中分配的对象或对象成员。如果类成员占用的空间是在构造函数中动态分配的,我们就必须自定义析构函数,然后显式使用delete运算符来释放构造函数使用new运算符分配的内存,就像销毁普通变量一样。我们需要在编写析构函数方面实践一下,因此下面就来试一试。
试一试:简单的析构函数
为了解何时调用类的析构函数,我们可以在CBox类中添加析构函数。下面是本示例的代码,其中包括的CBox类有一个析构函数:
- //Ex8_01.cpp
- //Classwithanexplicitdestructor
- #include<iostream>
- usingstd::cout;
- usingstd::endl;
- classCBox
//Classdefinitionatglobalscope - {
- public:
- //Destructordefinition
- ~CBox()
- {
- cout<<"Destructorcalled."<<endl;
- }
- //Constructordefinition
- CBox(doublelv=1.0,doublewv=1.0,doublehv=1.0):
- m_Length(lv),m_Width(wv),m_Height(hv)
- {
- cout<<endl<<"Constructorcalled.";
- }
- //Functiontocalculatethevolumeofabox
- doubleVolume()const
- {
- returnm_Length*m_Width*m_Height;
- }
- //Functiontocomparetwoboxeswhichreturnstrue
- //ifthefirstisgreaterthatthesecond,andfalseotherwise
- intcompare(CBox*pBox)const
- {
- returnthis->Volume()>pBox->Volume();
- }
- private:
- doublem_Length;
//Lengthofaboxininches - doublem_Width;
//Widthofaboxininches - doublem_Height;
//Heightofaboxininches - };
- //FunctiontodemonstratetheCBoxclassdestructorinaction
- intmain()
- {
- CBoxboxes[5];
//ArrayofCBoxobjectsdeclared - CBoxcigar(8.0,5.0,1.0);//Declarecigarbox
- CBoxmatch(2.2,1.1,0.5);//Declarematchbox
- CBox*pB1=&cigar;
//Initializepointertocigarobjectaddress - CBox*pB2=0;
/ /PointertoCBoxinitializedtonull - cout<<endl
- <<"Volumeofcigaris"
- <<pB1->Volume();
//Volumeofobj.pointedto - pB2=boxes;
//Settoaddressofarray - boxes[2]=match;
//Set3rdelementtomatch - cout<<endl
- <<"Volumeofboxes[2]is"
- <<(pB2+2)->Volume();//Nowaccessthrupointer
- cout<<endl;
- return0;
- }
示例说明
CBox类的析构函数仅仅显示一条宣称"析构函数被调用"的消息。该示例的输出如下:
- Constructorcalled.
- Constructorcalled.
- Constructorcalled.
- Constructorcalled.
- Constructorcalled.
- Constructorcalled.
- Constructorcalled.
- Volumeofcigaris40
- Volumeofboxes[2]is1.21
- Destructorcalled.
- Destructorcalled.
- Destructorcalled.
- Destructorcalled.
- Destructorcalled.
- Destructorcalled.
- Destructorcalled.