在基类中使用了 C++ 中的虚拟析构函数,因此派生类对象也可以被销毁。 虚拟析构函数是通过使用 ~ 波浪号运算符,然后在构造函数之前使用 virtual
关键字来声明的。
注意:构造函数不能是虚函数,但析构函数可以是虚函数。
不使用虚拟析构函数的示例
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"Base constructor is called"<<"\n";
}
~Base()
{
cout<<"Base class object is destroyed"<<"\n";
}
};
class Derived:public Base
{
public:
Derived()
{
cout<<"Derived class constructor is called"<<"\n";
}
~Derived()
{
cout<<"Derived class object is destroyed"<<"\n";
}
};
int main()
{
Base* b= new Derived;
delete b;
return 0;
}
输出结果:
Base constructor is called
Derived class constructor is called
Base class object is destroyed
在上面的例子中,delete b
只会调用基类析构函数,因为派生类析构函数保持未销毁。 这会导致内存泄漏。
带有虚拟析构函数的示例:
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"Base constructor is called"<<"\n";
}
virtual ~Base()
{
cout<<"Base class object is destroyed"<<"\n";
}
};
class Derived:public Base
{
public:
Derived()
{
cout<<"Derived class constructor is called"<<"\n";
}
~Derived()
{
cout<<"Derived class object is destroyed"<<"\n";
}
};
int main()
{
Base* b= new Derived;
delete b;
return 0;
}
运行结果:
Base constructor is called
Derived class constructor is called
Derived class object is destroyed
Base class object is destroyed
当我们使用虚析构函数时,那么先调用派生类析构函数,再调用基类析构函数。