c++虚析构函数的使用及其注意点

// ConsoleApplication33.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
#define  _CRT_SECURE_NO_WARNINGS
class A
{
public:

	A(A* a) 
	{
		cout << "1" << endl;
	}
	A(const A&a)
	{

		cout << "A copy" << this << endl;
	}
	A()
	{
		p = new char[20];
		strcpy_s(p, 2, "a");
		cout<<"A():"<<this << endl;
	}
	virtual  ~A()
	{
		if(p!=NULL)
		delete[] p;
		cout<<" ~A():"<<this << endl;
	}
	 int k = 4;
public:
	char *p;

};
class B :public A
{
public:
	B()
	{
		p = new char[20];
		strcpy_s(p, 3, "aa");
		cout<<"B():" << this <<endl;
	}
	~B()
	{
		delete[] p;
		cout << "~B():" << this << endl;
	}
public:
	char *p;

};

class C :public B
{
public:
	C()
	{
		p = new char[20];
		strcpy_s(p, 4, "aaa");
		cout << "C():" << this << endl;
	}
	~C()
	{
		delete[] p;
		cout << "~C():" << this << endl;
	}
public:
	char *p;
	int m = 3;

};

void howtodelete(A* base)
{
	delete base;
}


int main()
{

	A* a = NULL;
	//注意  使用指针这里一定要new 然后才能用父类指针去接收 否则会出错 new delete要配对
	C* c1=new C;
	a = &(*c1);
	howtodelete(a);

	system("pause");
}

  

原文地址:https://www.cnblogs.com/kexb/p/5539614.html