虚析构

虚析构用于释放子类中的指针成员

虚析构函数使得在删除指向子类对象的基类指针时,可以调用子类的析构函数来实现释放子类中堆内存的目的,从而防止内存泄漏。

示例:
.h

#pragma once

#include<iostream>
using namespace std;

class Parent {
public:
	Parent() :a(1), b(2), c(3)
	{

		p = new char[10];
		//strcpy(p, "abc");
		cout << "parent 无参构造。。。\n";
	}
	Parent(int test) :a(4), b(5), c(6)
	{
		p = new char[10];
		//strcpy(p, "abc");
		cout << "parent 有参构造。。。\n";
	}
	virtual ~Parent()
	{
		delete[] p;
		cout << "Parent 析构。。。\n";
	}
	int a;
	int b;
	int c;
	char *p;
	void p_print()
	{
		cout << "a b c is" << a << " " << b << " " << c << endl;
	}
	virtual void Print()
	{
		cout << "a b c is" << a << " " << b << " " << c << endl;
	}
};
class Child1 : public Parent
{
public:
	Child1() :Parent(1), a(10), b(11), c(12)
	{
		p = new char[10];
		//    strcpy(p, "abc");
		cout << "child1 构造\n";
	}
	virtual ~Child1()
	{
		delete[] p;
		cout << "child1 析构,,,\n";
	}
	void c1_print()
	{
		cout << "a b c is" << a << " " << b << " " << c << endl;
	}
	virtual void Print()
	{
		cout << "a b c is" << a << " " << b << " " << c << endl;
	}

	int a;
	int b;
	int c;
	char *p;
};
class Child2 : public Child1
{
public:
	Child2() :Child1(), b(22), c(23)
	{
		p = new char[10];
		//strcpy(p, "abc");
		cout << "child2 构造\n";
	}
	~Child2()
	{
		delete[] p;
		cout << "child2 析构,,,\n";
	}
	void c2_print()
	{
		cout << "a b c is" << Parent::a << " " << b << " " << c << endl;
	}
	/*virtual void Print()
	{
		cout << "a b c is" << a << " " << b << " " << c << endl;
	}*/
	//int a;
	int b;
	int c;
	char *p;
};
/*
class Child3 : public Child1, public Child2
{
public:
	Child3() : Child1(), Child2(), b(20), c(30) { cout << "child 构造\n"; }
	~Child3()
	{
		cout << "child 析构,,,\n";
	}
	void c3_print()
	{
		cout << "a b c is" << a << " " << b << " " << c << endl;
	}
	//int a;
	int b;
	int c;
};
*/

.cpp

// 虚析构测试.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include "parent.h"
#include <stdio.h>

void play(Parent* c2)
{
	//Child2* c2 = new Child2;
	delete c2;
}

int main()
{
	Child2* c2 = new Child2;
	c2->Print();
	play(c2);
		
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值