zoukankan      html  css  js  c++  java
  • 虚析构函数

    1、什么是虚析构函数?

    将一个类的虚函数定义成虚函数,这个析构函数就叫虚析构函数。
    注意:不允许以虚函数作为构造函数

    2、为什么提倡把带有虚函数的类的析构函数写为虚析构函数

    通过基类的指针删除派生类对象时,通常情况下只调用基类的析构函数。但是,删除一个派生类的对象时,应该先调用派生类的析构函数,然后调用基类的析构函数。因此,我们可以引入虚析构函数解决这个问题。即:将基类的西沟函数生命为虚函数。

    3、基类、派生类虚析构函数的特点

    • 一般来说,一个类如果定义了虚函数,则应该将析构函数也定义成 虚函数。
    • 或者,一个类打算作为基类使用,也应该将析构函数定义 成虚函数。
    • 派生类的析构函数可以virtual不进行声明

    3、虚析构函数的执行过程

    通过基类的指针删除派生类对象时:

    • 首先调用派生类的析构函数
    • 然后调用基类的析构函数

    4、举栗子

    //版本一:不定义虚析构函数
    class son{
    public:
    	~son() {cout<<"bye from son"<<endl;};
    };
    class grandson:public son{
    public:
    	~grandson(){cout<<"bye from grandson"<<endl;};
    };
    int main(){
    	son *pson;
    	pson=new grandson();
    	delete pson;
    	return 0;
    }
    //输出: bye from son 没有执行grandson::~grandson()!!!
    
    //版本二:定义虚析构函数
    class son{
    public:
    	virtual ~son() {cout<<"bye from son"<<endl;};
    };
    
    class grandson:public son{
    public:
    	~grandson(){cout<<"bye from grandson"<<endl;};
    };
    int main() {
    	son *pson;
    	pson= new grandson();
    	delete pson;
    	return 0;
    }
    /*
    输出: bye from grandson
    bye from son
    执行grandson::~grandson(),引起执行son::~son()!!!
    */
    
  • 相关阅读:
    OpenStack平台监控脚本-基础版
    制作rpm包,可以免除多次编译安装
    openstack安装指南
    服务器状态持续监控脚本
    搭建OpenStack私有云准备工作
    一键配置openstack-cata版的在线yum源
    openstack的yum源出错,配置openstack-ocata版的在线yum源,openstack的yum源配置
    py小结一
    Windows在cmd界面运行C++程序
    数字三角形「动态规划」
  • 原文地址:https://www.cnblogs.com/lasnitch/p/12764243.html
Copyright © 2011-2022 走看看