Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1071289
  • 博文数量: 242
  • 博客积分: 10209
  • 博客等级: 上将
  • 技术积分: 3028
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-12 09:27
文章分类

全部博文(242)

文章存档

2014年(1)

2013年(1)

2010年(51)

2009年(65)

2008年(124)

我的朋友

分类: C/C++

2009-10-13 15:04:19

//文件 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!


我们由此可以知道虚析构函数的使用场合:当用一个基类的指针删除一个派生类的对象时,为了让派生类的析构函数会被调用,需要基类的析构函数为虚函数。
阅读(712) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~