c++中虚函数与虚析构函数有什么用

发布时间:2022-01-14 17:18:11 作者:小新
来源:亿速云 阅读:131

这篇文章主要介绍了c++中虚函数与虚析构函数有什么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

虚函数与虚析构函数虚函数与虚析构函数

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

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

下面我们就来给析构函数的前面加上保留字 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 类的构造函数里申请了内存资源,就会造成内存泄漏了。

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

感谢你能够认真阅读完这篇文章,希望小编分享的“c++中虚函数与虚析构函数有什么用”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

推荐阅读:
  1. C++虚函数与非虚函数的区别。
  2. C++中的虚函数、纯虚函数

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:Spark 3.0怎么实现event logs滚动

下一篇:springboot整合quartz定时任务框架的方法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》