zoukankan      html  css  js  c++  java
  • c++中为什么析构函数要被设置为虚函数(virtual)

    1.如果类A可能会被继承,那么A的析构函数一定要被设置为virtual虚函数;

     原因:如果基类的析构函数不是虚函数,当创建一个基类指针指向一个派生类对象,当释放此基类指针时,子类的析构函数不会被调用;

     如下:

    class CFather
    {
    public:
        CFather();
        virtual ~CFather();
        
    public:
        virtual void test();
        //virtual void getHouse() = 0;
        
    public:
        int b;
        static const int c = 5;
    };
    
    CFather::CFather()
    {
        infof("CFather...create! g_test:%d
    ", g_test++);
    }
    
    CFather::~CFather()
    {
        infof("~CFather...destory
    ");
    }
    
    void CFather::test()
    {
        infof("CFather...test
    ");
    }
    
    
    class CChild : public CFather
    {
    
    public:
        CChild();
        ~CChild();
    public:
    
        void test();
        virtual void getHouse();
    private:
        int e;
    };
    
    CChild::CChild()
    {
        infof("CChild...create:g_test:%d
    ", g_test++);
    }
    
    CChild::~CChild()
    {
        infof("~CChild...destory
    ");
    }
    
    void CChild::test()
    {
        infof("CChild...test
    ");
    }
    
    void CChild::getHouse()
    {
        infof("CChild getHouse
    ");
    }
    int main()
    {
        Infra::setPrintLogLevel(6);
    
        CFather * cpt = new CChild;
    
        delete cpt;
            
        return 0;
    }

    输出结果:

    CFather...create! g_test:100
    
    CChild...create:g_test:20
    
    
    
     ~CChild...destory
    
    ~CFather...destory 
  • 相关阅读:
    面试题链接
    75 道 BAJT 高级 Java 面试题,你能答上几道?
    使用UML描述需求都实现的过程
    java面试题(下)
    golang中goconfig包使用解析
    golang中sublime text中配置goimports
    golang中new和make区别
    golang中并发sync和channel
    使用go build 进行条件编译
    golang中time包用法
  • 原文地址:https://www.cnblogs.com/weiyouqing/p/13850438.html
Copyright © 2011-2022 走看看