虚析构用于释放子类中的指针成员
虚析构函数使得在删除指向子类对象的基类指针时,可以调用子类的析构函数来实现释放子类中堆内存的目的,从而防止内存泄漏。
示例:
.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;
}