今天,我们将会在这篇文章中为大家详细介绍一下C++虚析构函数的一些基本知识。相信对于刚刚接触C++编程语言的初学者们现在急需要诸如这方面的基础知识的讲解内容,以加大自己对这一语言的认知。#t#
C++的多态性是通过虚函数来实现的,虚函数的出现使得动态链接成为可能。
基于构造函数的特点,不能将构造函数定义为虚函数,但可以将析构函数定义为虚函数。当派生类的对象从内存中撤销时,会先调用派生类的析构函数,然后自动调用基类的析构函数,如此看来析构函数也没有必要定义为虚函数。
但是考虑如下这种情况,如果使用基类指针指向派生类的对象,而这个派生类对象恰好是用new运算创建的,这种情况下会如何呢?当程序使用delete运算撤销派生类对象时,这时只会调用基类的析构函数,而没有调用派生类的析构函数。如果使用的是虚析构函数的话,就不一样了,所以定义虚析构函数有时候还是很有必要的。下面这段程序就说明了上面的问题:
没有定义虚C++虚析构函数时,code如下:
#include < iostream>
using namespace std;
class A
{
public:
A(){}
~A()
{
cout< < "A::destructor"< < endl;
}
};
class B:public A
{
public:
B(){}
~B()
{
cout< < "B::destructor"< < endl;
}
};
int main()
{
A *pA = new B;
//
delete pA;
return 0;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
输出的是A::destructor
这说明delete pA只是调用了基类A的析构函数,而没有调用子类B的析构函数,这不是我们所想要的。而把基类A的析构函数定义为虚函数后,就可以达到了我们所想要的效果了。code如下:
#include < iostream>
using namespace std;
class A
{
public:
A(){}
virtual ~A()
{
cout< < "A::destructor"< < endl;
}
};
class B:public A
{
public:
B(){}
~B()
{
cout< < "B::destructor"< < endl;
}
};
int main()
{
A *pA = new B;
//
delete pA;
return 0;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
输出如下:
B::destrutor
A::destrutor
以上就是对C++虚析构函数的相关介绍。