• 虚析构函数


    class BaseClass
    {
    public:
    	BaseClass() {}
    	~BaseClass() 
    	{
    		std::cout << "delete BaseClass" << std::endl;
    	}
    };
     
    class ChildClassA : public BaseClass
    {
    public:
    	ChildClassA() {}
    	~ChildClassA() 
    	{
    		std::cout << "ChildClassA Delete" << std::endl;
    	}
    };
    class ChildClassB : public ChildClassA
    {
    public:
    	ChildClassB() {}
    	~ChildClassB()
    	{
    		std::cout << "ChildClassB Delete" << std::endl;
    	}
    };
    void main(){
        // 测试案例
        BaseClass *a = new ChildClassA();
    	BaseClass *b = new ChildClassB();
    	ChildClassA *c = new ChildClassB();
     
    	delete a;
    	a = nullptr;
    	std::cout << std::endl;
     
    	delete b;
    	b = nullptr;
    	std::cout << std::endl;
     
    	delete c;
    	c = nullptr;
    }
    //delete BaseClass
    //
    //delete BaseClass
    //
    //ChildClassA Delete
    //delete BaseClass
    class BaseClass
    {
    public:
    	BaseClass() {}
    	virtual ~BaseClass() 
    	{
    		std::cout << "delete BaseClass" << std::endl;
    	}
    };
    //ChildClassA Delete
    //delete BaseClass
    //
    //ChildClassB Delete
    //delete BaseClass
    //
    //ChildClassB Delete
    //ChildClassA Delete
    //delete BaseClass

     虚析构函数:当基类指针指向子类对象的时候,需要把基类的析构函数设置成虚析构,防止内存泄露

  • 相关阅读:
    第三周作业
    第二周作业
    计算机基础学习心得
    第三次作业
    第2次作业(指针总结)
    2018(上)C高级第0次作业
    本学期最后一次作业 总结。
    第十四、十五周作业
    第七周作业
    第六周作业
  • 原文地址:https://www.cnblogs.com/wuyuan2011woaini/p/16381285.html
Copyright © 2020-2023  润新知