析构函数是虚函数时

来源:互联网 发布:数据库概论答案 编辑:程序博客网 时间:2024/06/01 07:57
#include <iostream>#include <cstring>using namespace std;class A{public:A(){ p(); }virtual void p(){ cout << "a" << endl; } ~A(){ p(); }};class B :public A{public:B(){ p(); }void p(){ cout << "B" << endl; }~B(){ p(); }};int main(int, char**){A* a = new B();delete a;// a  B  a  此时派生类没有被释放cout << "********" << endl;B *b = new B();delete b;// a  B B a   当释放派生类时,先释放基类,后释放派生类。return 0;}
给A类中析构函数是虚函数时
#include <iostream>#include <cstring>using namespace std;class A{public:A(){ p(); }virtual void p(){ cout << "a" << endl; }virtual ~A(){ p(); }};class B :public A{public:B(){ p(); }void p(){ cout << "B" << endl; }~B(){ p(); }};int main(int, char**){A* a = new B();delete a;            // a  B B a cout << "********" << endl;B *b = new B();delete b;return 0;}
#include <iostream>#include <cstring>using namespace std;class A{public:A(){ p(); }virtual void p(){ cout << "a" << endl; }virtual ~A(){ p(); }};class B :public A{public:B(){ p(); }void p(){ cout << "B" << endl; }~B(){ p(); }};int main(int, char**){cout << "********" << endl;A c;                    //acout << "********" << endl;B d;                   // a Bcout << "********" << endl;A* a = new B();        //a Bdelete a;              //B acout << "********" << endl;B *b = new B();        //a Bdelete b;              //B areturn 0;              // B a(先释放d对象的析构)  a(再释放c对象的析构)}
// 其中 对象c、d是在return 0时释放的。