虚析构函数

#include<iostream>
using namespace std;

class A
{
public:
    A()
    {
         cout << "A()..." << endl;
         this->p = new char[64];
         memset(this->p,0,64);//清空数组
         strcpy(this->p,"A String...");
    }

    virtual void print()
    {
        cout << "A:" << this->p << endl;
    }

    virtual ~A() {//虚析构函数
        cout << "~A()..." << endl;
        if (this->p != NULL) {
            delete[] this->p;
            this->p = NULL;
        }
    }
private:
    char *p;
};

class B :public A
{
public:
    B()
    {//此刻一定会触发A的无参构造
         cout << "B()..." << endl;
         this->p = new char[64];
         memset(this->p,0,64);//清空数组
         strcpy(this->p,"B String...");
    }

    virtual void print()
    {
        cout << "B:" << this->p << endl;
    }

    virtual ~B()
    {
        cout << "~B()..." << endl;
        if (this->p != NULL) {
            delete[] this->p;
            this->p = NULL;
        }
    }

private:
    char *p;
};

void func(A *ap)
{
    ap->print();//在此发生多态

    delete ap;//要使此刻ap-> ~B(),~B()再自动触发~A()
            //即让此刻产生多态,要使用虚析构函数,
            //不然系统默认触发~A(),不再触发~B(),会发生内存泄漏
}

void test()
{
    A *ap = new A;
    func(ap);
    cout << "-------------"<< endl;

    B *bp = new B;
    func(bp);
}
int main()
{
    test();   
    return 0;
}

总结:

void func(A *ap)
  {
    ap->print();//在此发生多态

    delete ap;//要使此刻ap-> ~B(),~B()再自动触发~A()
        //即让此刻产生多态,要使用虚析构函数,
        //不然系统默认触发~A(),不再触发~B(),会发生内存泄漏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值