C++虚析构函数

423阅读 0评论2009-10-13 wqfhenanxc_cu
分类:C/C++

//文件 Clx.h
#include "iostream.h"

class ClxBase
{
public:
    ClxBase() {};
    virtual ~ClxBase() {
        cout <<"Output from the destructor of class ClxBase!"<    };

    virtual void DoSomething() {
        cout << "Do something in class ClxBase!" << endl;
    };
};

class ClxDerived : public ClxBase
{
public:
    ClxDerived() {};
    ~ClxDerived() {
        cout << "Output from the destructor of class ClxDerived!" << endl;
    };

    void DoSomething() {
        cout << "Do something in class ClxDerived!" << endl;
    };
};

//文件test.cpp
#include "Clx.h"

int main(){

    ClxBase *pTest = new ClxDerived;
    pTest->DoSomething();
    delete pTest;

    printf("***************\n")
   
    ClxDerived a;
    a.DoSomething();
    return 0;
}

上面程序的输出结果为:

Do something in class ClxDerived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!
***************
Do something in class ClxDerived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!

如果把ClxBase类中的虚析构函数改为 非虚析构函数,则输出结果为:

Do something in class ClxDerived!
Output from the destructor of class ClxBase!
***************
Do something in class ClxDerived!
Output from the destructor of class ClxDerived!
Output from the destructor of class ClxBase!


我们由此可以知道虚析构函数的使用场合:当用一个基类的指针删除一个派生类的对象时,为了让派生类的析构函数会被调用,需要基类的析构函数为虚函数。
上一篇:C++ inline 函数 ZZ
下一篇:C++ new ZZ