本文主要是介绍与虚函数相关的几点注意之二——虚析构函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
【原文写于 21 January 2007 ,注】虚析构函数
对于基类(或者设计成将被派生的类),析构函数应被声明为虚函数。虚析构函数能够保证派生类被正确析构
class ClassBase
{
public:
~ClassBase() { printOut(”Deconstructor in Base Class”); }
};class ClassDerived : public ClassBase
{
public:
~ClassDerived() { printOut(”Deconstructor in Derived Class”); }
};void main()
{
ClassBase p = new ClassDerived;
delete p;
}
将打印”Deconstructor in Base Class”
class ClassBase
{
public:
virtual ~ClassBase() { printOut(”Deconstructor in Base Class”); }
};class ClassDerived : public ClassBase
{
public:
~ClassDerived() { printOut(”Deconstructor in Derived Class”); }
};void main()
{
ClassBase p = new ClassDerived;
delete p;
}
将打印
”
Deconstructor in Derived Class
Deconstructor in Base Class
“
这篇关于与虚函数相关的几点注意之二——虚析构函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!