一、基類析構函數爲虛函數
#include <iostream>
using namespace std;
class Point
{
public:
Point(){
cout << "Point()" << endl;
}
virtual ~Point(){
cout << "~Point()" << endl;
}
};
class Point3d : public Point
{
public:
Point3d(){
cout << "Point3d()" << endl;
}
~Point3d(){
cout << "~Point3d()" << endl;
}
};
int main()
{
Point *p = new Point;
delete p;
cout << "-------------------" << endl;
Point *p3d = new Point3d;
delete p3d;
cout << "-------------------" << endl;
Point3d *ps = new Point3d;
delete ps;
cout << "-------------------" << endl;
Point *psa = new Point3d[2];
delete psa;
cout << "-------------------" << endl;
Point *psb = new Point3d[2];
delete []psb;
cout << "-------------------" << endl;
return 0;
}
執行結果:
上面代碼的執行結果均符合我們正常的多態需要。
二、基類析構函數不是虛函數
代碼爲去掉上面代碼中基類析構函數中前的 virtual,執行結果爲:
這次,我們發現幾個由基類指針指向的子類對象並沒有正確調用析構函數,釋放內存。這說明,delete 釋放對象內存的時候,需要注意兩個方面的問題:
1、如果基類有虛擬析構函數,則可以直接通過基類指針釋放子類的內存;
2、如果基類沒有虛擬析構函數,則需要將指向子類對象的指針強轉爲子類類型後,傳遞給delete;
3、在繼承體系中,我們的析構函數只需管理本類新引入的動態內存,而不需要關心父類中的內存管理;