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()!!!
    */
    
  • 相关阅读:
    关于lockkeyword
    关于多层for循环迭代的效率优化问题
    Android 面试精华题目总结
    Linux基础回想(1)——Linux系统概述
    linux源代码编译安装OpenCV
    校赛热身 Problem C. Sometimes Naive (状压dp)
    校赛热身 Problem C. Sometimes Naive (状压dp)
    校赛热身 Problem B. Matrix Fast Power
    校赛热身 Problem B. Matrix Fast Power
    集合的划分(递推)
  • 原文地址:https://www.cnblogs.com/lasnitch/p/12764243.html
Copyright © 2011-2022 走看看