欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c++-虚析构函数

程序员文章站 2022-08-02 22:00:21
虚析构函数 ......

虚析构函数

#define _crt_secure_no_warnings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>


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();//在此发生多态

}

void deletefunc(a *ap)
{
    delete ap; //此刻ap->~b() //~b() ---> ~a()
}

void test()
{
    //a *ap = new a;
    //func(ap);
    b *bp = new b;
    func(bp);

    deletefunc(bp);
}

int main(void)
{
    test();
    

    b bobj;

    //bobj.~b();
    return 0;
}