C++day06 虚析构函数

大家好,我是阿林。今天我和大家分享的是虚析构函数。

当我们析构函数不使用virtual时,当用继承的父类的子类使用析构函数时他只会调用父类的析构函数,想要解决这个问题,必须使用虚析构函数。

现在让我们看看代码是怎么实现虚析构函数的。

#include 


using namespace std;

//虚析构函数
class A
{
public:
	A()
	{
		p = new char[20];
		strcpy(p, "obja");
		printf("A()\n");
	}
	virtual ~A()
	{
		delete[] p;
		printf("~A()\n");
	}

protected:
private:
	char* p;
};

class B : public A
{
public:
	B()
	{
		p = new char[20];
		strcpy(p, "objb");
		printf("B()\n");
	}
	~B()
	{
		delete[] p;
		printf("~B()\n");
	}
protected:
private:
	char* p;
};

class C : public B
{
public:
	C()
	{
		p = new char[20];
		strcpy(p, "objc");
		printf("C()\n");
	}
	~C()
	{
		delete[] p;
		printf("~C()\n");
	}
protected:
private:
	char* p;
};


//只执行父类的虚构函数
//想通过父类指针 把 所有子类对象的析构函数 都是执行一遍
//想通过父类指针 释放所有得子类资源
void howtodelete(A* base)
{
	delete base; //这句话不会表现出多态,这种属性,因为在析构函数中没有加上virtual
}

int main()
{
	C* myC = new C;
	howtodelete(myC);
	system("pause");
	return 0;
}

你可能感兴趣的:(c++,开发语言)