现在的位置: 首页 > 编程语言 > 正文

虚函数与虚析构函数

2019年03月30日 编程语言 ⁄ 共 1850字 ⁄ 字号 评论关闭
虚函数与虚析构函数
虚函数与虚析构函数

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

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

下面我们就来给析构函数的前面加上保留字 virtual,看看运行的结果会怎么样:

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

  1. //cat.h
  2. #include "animal.h"
  3. class Cat : public Animal
  4. {
  5.     public:
  6.         Cat(int w = 0, int a = 0);
  7.         ~Cat();
  8. };
  9. Cat::Cat(int w, int a):Animal(w, a)
  10. {
  11.     cout <<"Cat
    constructor is running..."
     <<endl;
  12. }
  13. Cat::~Cat()
  14. {
  15.        cout <<"Cat
    destructor is running..."
     <<endl;
  16. }

  1. //main.cpp
  2. #include "cat.h"
  3. int main(void)
  4. {
  5.     Animal *pa=new
    Cat(2,1);
  6.     Cat *pc=new
    Cat(2,4);
  7.     cout <<">>>
    Delete pa <<<"
     <<endl;
  8.     delete pa;
  9.     cout <<">>>
    Delete pc <<<"
     <<endl;
  10.     delete pc;
  11.     return 0;
  12. }

运行结果:
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...

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

我们修改程序,将 Animal 类析构函数前的 virtual 去掉
运行结果:
Animal consturctor is running...
Cat constructor is running...
Animal consturctor is running...
Cat constructor is running...
>>> Delete pa <<<
Animal destructor is running...
>>> Delete pc <<<
Cat destructor is running...
Animal destructor is running...

    发现运行结果中删除 pa 指向的 Cat 对象时,不执行 Cat 类的析构函数。如果这时 Cat 类的构造函数里申请了内存资源,就会造成内存泄漏了。

所以说,虚函数与虚析构函数的作用是不同的。虚函数是为了实现多态,而虚析构函数是为了同时运行父类和子类的析构函数,使资源得以释放

转自http://blog.chinaunix.net/uid-26495963-id-3343923.html

抱歉!评论已关闭.