zoukankan      html  css  js  c++  java
  • 为什么一般要定义析构函数为虚析构函数

    没有使用虚析构函数可能会出现的问题:

    #include <iostream>
    #include <string>
    using namespace std;
    
    class A {
    public:
    	A() { cout << "A constructor" << endl; }
    	~A() { cout << "A destructor" << endl; }
    };
    
    class B: public A {
    	char *buf;
    public:
    	B() { buf = new char[10]; cout << "B constructor" << endl; }
    	~B() { cout << "B destructor" << endl; }
    };
    
    int main()
    {
    	A *p = new B;
    	delete p;  // p是基类类型指针,仅调用基类析构函数,造成B中申请的10字节内存没被释放。
    	return 0;
    }
    
    

    输出:

    A constructor
    B constructor
    A destructor

    解决:将基类中的析构函数定义为虚析构函数

    #include <iostream>
    #include <string>
    using namespace std;
    
    class A {
    public:
    	A() { cout << "A constructor" << endl; }
    	virtual ~A() { cout << "A destructor" << endl; }
    };
    
    class B: public A {
    	char *buf;
    public:
    	B() { buf = new char[10]; cout << "B constructor" << endl; }
    	~B() { cout << "B destructor" << endl; }
    };
    
    int main()
    {
    	A *p = new B;
    	delete p; //A中的析构函数说明为虚析构函数后,B中析构函数自动成为虚析构函数,由于P
                      //指向派生类对象,因此会调用派生类B的析构函数。
    	return 0;
    }
    
    

    输出:

    A constructor
    B constructor
    B destructor
    A destructor

  • 相关阅读:
    对于CD翻录的一些记录
    暑期实践
    暑期实践
    垃圾处理器-CMS
    离合器半联动点的判断和技巧
    Win10+VS2019+OpenCV环境配置
    C++ 学习资料
    科目二起步原理
    道路交通安全违法行为记分分值分类总结
    NWERC 2020 题解
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2858785.html
Copyright © 2011-2022 走看看