Which statement is false?
a) Destructors are called when a pointer is deleted.
b) Destructors are called when an object goes out of scope.
c) Destructors are called when a reference goes out of scope.
d) A virtual destructor should be used if the class has virtual methods.
e) Base class destructors are called after derived class destructors.
/*
关于析构
Which statement is false?
a) Destructors are called when a pointer is deleted.
b) Destructors are called when an object goes out of scope.
c) Destructors are called when a reference goes out of scope.
d) A virtual destructor should be used if the class has virtual methods.
e) Base class destructors are called after derived class destructors
*/
#include "stdafx.h"
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
class Parent
{
public:
virtual ~Parent()
{
cout << "~Parent" << endl;
}
virtual void func(){
cout << "Parent->func"<<endl;
}
};
class Son:public Parent
{
public:
virtual ~Son()
{
cout << "~Son" << endl;
}
virtual void func(){
cout << "Son->func" << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
//Parent * pParent = new Parent;
//{
// Parent p; //超出作用域也要调用析构函数
//}
//cout << "delete pParent..." << endl;
//delete pParent; // delete对象指针时会调用析构函数
////////////////////////////////////////////////////////////////////////////
//Parent p;
//{
// Parent& rP = p; //引用超出作用域时,是不会析构对象的,只是“引用而已”
//}
//当通过子类指针析构子类对象 或者 子类对象超过作用域时
//不管析构函数是否是虚函数,都是先执行子类的析构函数,
//再调用父类的析构函数,这跟构造时的顺序相反
//Son s;
//Son * s = new Son;
//delete s;
//当通过父类指针析构子类对象时,如果
//析构函数是虚函数,则delete时,根据子类对象的虚函数表,查到要调用的
//析构韩式是子类的版本,这时调用子类的析构函数,然后析构父类,才调用父类
//的析构函数
//但当析构函数不是虚函数时,将直接调用父类的析构函数,而不会调用子类的析构函数,会造成资源泄漏
//所以一般有继承关系的类,都要将析构函数定义为虚函数
Parent * s = new Son;
//s->func();
delete s;
}
另外,对于virtual这个关键词,一般在父类中的方法定义了之后,子类不需再写virtual也是虚函数,但为了清楚起见,凡是虚函数都最好写上virtual