#include <iostream> using namespace std; class A{ public: A() { cout<<"construct A"<<endl; } virtual void disp() { cout<<"AAAA"<<endl; } virtual ~A() //析构函数一般必须声明为虚函数 { cout<<"destory A"<<endl; } }; class B:public A { public: B() { cout<<"construct B"<<endl; } virtual void disp(int a) { cout<<"BBBB"<<endl; } ~B() { cout<<"destory B"<<endl; } }; int main() { A *a=new A(); B *b=new B(); delete b; return 0; }
析构函数:
- 栈内变量,自动析构 eg. A a; //a自动析构
- 堆内 A *pa = new A(); //要程序员自己析构 ,delete pa;
构造顺序:
1. 先构造基类,再构造派生类
析构顺序:(与构造相反)
1. 先析构派生类,再析构基类