虛析構函數

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		p = new char[20];
		strcpy(p, "abcdefg");
		cout << "A()" << endl;
	}
	~A()
	{
		delete[] p;
		cout << "~A()" << endl;
	}

private:
	char *p;

};


class B : public A
{
public:
	B()
	{
		p = new char[20];
		strcpy(p, "qwert");
		cout << "B()" << endl;
	}
	~B()
	{
		delete[] p;
		cout << "~B()" << endl;
	}
private:
	char *p;
};

class C : public B
{
public:
	C()
	{
		p = new char[20];
		strcpy(p, "qwert");
		cout << "C()" << endl;
	}
	~C()
	{
		delete[] p;
		cout << "~C()" << endl;
	}
private:
	char *p;
};

/*
只執行了父類的析構函數  這樣會造成內存泄漏
想通過父類指針釋放所有的子類資源   需要 使用虛析構函數
*/
void howToDele(A *base)
{
	delete base;	// 如果沒有在析構函數中加virtual  這句話是不會表現出多態這種屬性的
}




int main()
{
	C *myC = new C;
	// howToDele(myC);

	/*
	直接通過子類對象釋放資源, 不需要在析構函數上寫=加virtual
	*/
	delete myC;


	system("pause");
	return 1;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章