zoukankan      html  css  js  c++  java
  • C++类继承--基类析构函数加上Virtual

    下面的内容要说明两个问题:1. 基类的析构函数为什么要加上Virtual--防止内存泄露

    1. 基类虚构函数无virtual,派生类无法析构,会导致内存泄露

    #include <stdio.h>
    
    class Base
    {
    public:
    	int a;
    	Base(){
    		a=0;
    	}
    	~Base(){
    		printf("base delete");
    	}
    	virtual void setA()=0;
    };
    
    class A:public Base
    {
    public:
    	A(){
    		a = 10;
    	}
    	~A(){
    		printf("A class delete
    ");
    	}
    	virtual void setA()
    	{
    		a = 2;
    	}
    };
    
    class B:public Base
    {
    public:
    	B(){
    		a=20;
    	}
    	~B(){
    		a=-20;
    	}
    	
    	virtual void setA()
    	{
    		a = 3;
    	}
    };
    
    int main()
    {
    	
    	Base *ax = new A();
    	Base *bx = new B();
    	Base *aClass =  ax;
    	Base *bClass = bx;
    	printf("a value of a construct %d
    ", aClass->a);
    	printf("a value of b construct %d
    ", bClass->a);
    
    	aClass->setA();
    	bClass->setA();
    	printf("a value of a %d
    ", aClass->a);
    	printf("a value of b %d
    ", bClass->a);
    
    	delete aClass;
    	
    	return 0;
    }
    

      运行结果为:

    2. 若在基类析构函数前加上Virtual

    class Base
    {
    public:
    	int a;
    	Base(){
    		a=0;
    	}
    	virtual ~Base(){
    		printf("base delete");
    	}
    	virtual void setA()=0;
    	
    };
    

      运行结果为:

  • 相关阅读:
    网络流模型之二分图匹配问题
    省选测试8
    省选测试9
    省选测试7
    省选测试6
    网络流最大流、最小割学习笔记
    kruskal重构树学习笔记
    省选测试5
    Python 打包成exe 方式
    JQuery
  • 原文地址:https://www.cnblogs.com/anlia/p/9084104.html
Copyright © 2011-2022 走看看