C++中的虚析构函数的作用

虚析构函数的作用:

  1. 当直接delete子类的指针对象时,delete会先调用子类的析构函数,再调用父类的析构函数。
    #include
    using namespace std;
    
    class AA
    {
    public:
    	AA(int a = 0)
    	{
    		this->a = a;		
    	}
    	~AA()
    	{
    		cout << "AA类的虚析构函数" << endl;
    	}
    	virtual void print()
    	{
    		cout << "AA的print()函数" << endl;
    	}
    
    protected:
    	int a;
    private:
    };
    
    class BB:public AA
    {
    public:
    	BB(int a = 0, int b = 0)
    	{
    		this->a = a;
    		this->b = b;
    	}
    	~BB()
    	{
    		cout << "BB类的虚析构函数" << endl;
    	}
    	virtual void print()
    	{
    		cout << "BB类的print()函数" << a << "	" << b << endl;
    	}
    
    protected:
    private:
    	int b;
    };
    
    void howToDelete(AA *pBase)
    {
    	delete pBase;
    }
    
    void main()
    {
    	BB *b1 = new BB(1, 2);
    
    	b1->print();
    
    	delete b1;
    
    	cout << endl;
    
    	//howToDelete(b1);
    
    	system("pause");
    
    
    }
  2. 实验现象如下

你可能感兴趣的:(C++中的虚析构函数)