• 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 
  • 相关阅读:
    设计模式-单列模式
    linux udp c/s
    linux 命令
    java String
    [转]Android进程间通信--消息机制及IPC机制实现
    Android入门:Activity四种启动模式
    CRT 重启Was
    jquery.cookie.js 使用
    div设置contentEditable="true"作为文本编辑器,定位光标解决办法
    居中展示图片
  • 原文地址:https://www.cnblogs.com/weiyouqing/p/13850438.html
Copyright © 2020-2023  润新知