C++:虚析构函数

 首先,欢迎并感激博友进行知识补充与修正。


#include <iostream>
using namespace std;


//虚析构函数
class A
{
public:
	A()
	{
		p = new char[20];
		cout << "A()" << endl;
	}
	virtual ~A()
	{
		delete[] p;
		cout << "~A()" << endl;
	}
private:
	char *p;
};

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

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


//想通过父类指针把所有子类析构函数执行一遍(释放所有子类资源)
void play(A *p)
{
	delete p;
}
int main()
{
	C *myc = new C; //new delete相匹配
	play(myc);
    
    //直接通过子类指针释放资源,不需要virtual关键字
    //delete myc;

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/feissss/article/details/88061633