C++虚析构函数

匿名 (未验证) 提交于 2019-12-03 00:40:02

使用虚析构函数举例:

//本例演示析构函数需要被定义成虚函数的情况,注意构造函数是不可以被定义成虚函数的 #include<iostream> using namespace std; class Base{ public: 	~Base();				//virtual ~Base();	 }; Base::~Base(){ 	cout<<"Base destructor"<<endl; }  class Derived : public Base{ private: 	int *p; public: 	Derived(); 	~Derived();		//virtual ~Derived(); }; Derived::Derived(){ 	p = new int(0); } Derived::~Derived(){				 	cout<<"Derived destructor"<<endl;			 }  void fun(Base *b){ 	delete b; }  int main(){ 	Base *b = new Derived(); 	fun(b);				//由于会直接调用基类,所以在派生类中分配的空间不会被释放掉,造成内存泄露 					//解决方法是:将基类和派生类的析构函数声明为虚函数(即每行注释的代码) 	system("pause"); 	return 0; }

  

 

原文:https://www.cnblogs.com/xuelisheng/p/9280191.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!