Chinaunix首页 | 论坛 | 博客
  • 博客访问: 891968
  • 博文数量: 299
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2493
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-21 10:07
个人简介

Linux后台服务器编程。

文章分类

全部博文(299)

文章存档

2015年(2)

2014年(297)

分类: C/C++

2014-10-29 20:32:07

在类中,有两个与众不同的成员函数,那就是构造函数和析构函数。当构造函数与析构函数遭遇继承和多态,它们的运行状况又会出现什么变化呢?

多态性是在父类或各子类中执行最合适成员函数。一般来说,只会选择父类或子类中的某一个成员函数来执行。这可给析构函数带来了麻烦!如果有的资源是父类的构造函数申请的,有的资源是子类的构造函数申请的,而虚函数只允许程序执行父类或子类中的某一个析构函数,岂不是注定有一部分资源将无法被释放?为了解决这个问题,虚析构函数变得与众不同。

下面我们就来给析构函数的前面加上保留字virtual,看看运行的结果会怎么样:(程序17.8)
//animal.h

点击(此处)折叠或打开

  1. #include <iostream>
  2. using namespace std;
  3. class Animal
  4. {
  5.    public:
  6.    Animal(int w=0,int a=0);
  7.    virtual ~Animal();//虚析构函数
  8.    protected:
  9.    int weight,age;
  10. };
  11. Animal::Animal(int w,int a)
  12. {
  13.    cout <<"Animal consturctor is running..." <<endl;
  14.    weight=w;
  15.    age=a;
  16. }
  17. Animal::~Animal()
  18. {
  19.    cout <<"Animal destructor is running..." <<endl;
  20. }


//cat.h

点击(此处)折叠或打开

  1. #include "animal.h"
  2. class Cat:public Animal
  3. {
  4.    public:
  5.    Cat(int w=0,int a=0);
  6.    ~Cat();
  7. };
  8. Cat::Cat(int w,int a):Animal(w,a)
  9. {
  10.       cout <<"Cat constructor is running..." <<endl;
  11. }
  12. Cat::~Cat()
  13. {
  14.    cout <<"Cat destructor is running..." <<endl;
  15. }
  16. //main.cpp
  17. #include "cat.h"
  18. int main()
  19. {
  20.    Animal *pa=new Cat(2,1);
  21.    Cat *pc=new Cat(2,4);
  22.    cout <<"Delete pa:" <<endl;
  23.    delete pa;
  24.    cout <<"Delete pc:" <<endl;
  25.    delete pc;
  26.    return 0;
  27. }


运行结果:
Animal consturctor is running...
Cat constructor is running...
Animal consturctor is running...
Cat constructor is running...
Delete pa:
Cat destructor is running...
Animal destructor is running...
Delete pc:
Cat destructor is running...
Animal destructor is running...

我们惊讶地发现,虚析构函数不再是运行父类或子类的某一个析构函数,而是先运行合适的子类析构函数,再运行父类析构函数。即两个类的析构函数都被执行了,如果两块资源分别是由父类构造函数和子类构造函数申请的,那么使用了虚析构函数之后,两块资源都能被及时释放。

我们修改程序17.8,将Animal类析构函数前的virtual去掉,会发现运行结果中删除pa指向的Cat对象时,不执行Cat类的析构函数。如果这时Cat类的构造函数里申请了内存资源,就会造成内存泄漏了。

所以说,虚函数与虚析构函数的作用是不同的。虚函数是为了实现多态,而虚析构函数是为了同时运行父类和子类的析构函数,使资源得以释放。
阅读(1437) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~