c++-虚析构函数

2019-12-22 16:01:54来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

c++-虚析构函数

虚析构函数

#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;
}

原文链接:https://www.cnblogs.com/ygjzs/p/12079025.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:c++-多态的练习

下一篇:c++-多态和vptr指针